2

Je reçois une exception d'exécution sur l'affichage d'un message ToastMessageBody d'affichage de la notification Firebase comme Toast

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

Je veux afficher le corps du message comme un message Toast lorsque l'utilisateur reçoit une notification push de n'importe où dans l'application.

Toute aide?

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

On dirait que vous avez déjà 'Toast.makeText (...)' chaque fois que vous appelez 'sendNotification()'. Y a-t-il quelque chose qui ne va pas? –

+0

L'exception d'exécution que j'obtiens à chaque notification. –

+0

Droite. Je ne suis pas sûr que ce soit lié au Toast. Peut-être avec le contexte. Pouvez-vous éditer et mettre dans la pile complète? –

Répondre

6

Si vous voulez afficher Toast.Vous devez exécuter sur le thread UI;

Exemple:

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

Merci. Je vais faire le tour. –