Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase onMessageReceived(RemoteMessage remoteMessage), is not called when the app is in background [duplicate]

In Firebase onMessageReceived(RemoteMessage remoteMessage), this method will be called when your app is in Foreground. So, on clicking the notification you can open a different Activity, say NotiicationActivity.

But what if your app is in background, then this method will not be called, and on clicking the notification only a Launcher Activity will be opened.

So how to open the NotificationActivity on clicking the notification even if our app is in background.

My Code is this :

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

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

    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, NewActivity.class);
        intent.putExtra("key", messageBody);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
        Bitmap icon2 = BitmapFactory.decodeResource(getResources(),
            R.mipmap.ic_launcher);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("FCM Sample")
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setLargeIcon(icon2)
        .setSound(defaultSoundUri)
        .setContentIntent(pendingIntent);

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

        notificationManager.notify(new Random().nextInt() /* ID of notification */, notificationBuilder.build());
    }
}
like image 288
Aman Shekhar Avatar asked Dec 07 '16 05:12

Aman Shekhar


1 Answers

onMessageReceived is only triggered when the application is in foreground. If the app is backgrounded, you may still be able to receive the notification but onMessageReceived will not be triggered.

So my suggestion, on the receiving activity, you can still get the data from the notification by using:

getIntent().getExtras();

This should work accordingly. Hope this helps :)

like image 180
kenix Avatar answered Oct 29 '22 23:10

kenix