2

Я получаю исключение времени выполнения на дисплее появится сообщение ToastДисплей MessageBody из Firebase оповещении в Toast

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 

Я хочу, чтобы отобразить тело сообщения в виде сообщения Toast, когда пользователь получает толчок уведомление от в любом месте приложения.

Любая помощь?

public class MyAppFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "FCM Service"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
       if (remoteMessage.getNotification() != null) { 
      if (AppConfig.SYSTEM_WIDE_DEBUG) { 
       Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
      } 

      sendNotification(remoteMessage.getNotification().getBody()); 
     } 

    } 

    private void sendNotification(String messageBody) { 
     Toast.makeText(getApplicationContext(),messageBody,Toast.LENGTH_LONG).show(); 

     Intent intent = new Intent(this, HomeActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pushnotify); 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setContentTitle("My APP") 
       .setContentText(messageBody) 
       .setAutoCancel(true) 
       .setSound(defaultSoundUri) 
       .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
    } 
} 
+0

Похоже, у вас уже есть 'Toast.makeText (...)' каждый раз, когда вы звоните 'sendNotification()'. Здесь что-то не так? –

+0

Исключение во время выполнения, которое я получаю при каждом уведомлении. –

+0

Справа. Я не уверен, что это связано с Тостом. Возможно, с контекстом. Можете ли вы редактировать и вставлять полную стек? –

ответ

6

Если вы хотите показать Toast.You должен работать на UI Thread;

Пример:

Handler handler = new Handler(Looper.getMainLooper()); 
handler.post(new Runnable() { 
    public void run() { 
     Toast.makeText(getApplicationContext(),Toast.LENGTH_SHORT).show(); 
    } 
}); 
+0

Спасибо. Я займу экскурсию. –

Смежные вопросы