Search code examples
androidfirebasefirebase-cloud-messagingfirebase-notifications

Clicking on FCM notification opens currently closed activity not targeted activity


Here is my code, When my app is running in foreground it opens targeted activity but when app is closed or in background, it doesn't opens targeted activity, please help me to solve this problem

I want that by clicking on notification will open targeted activity even app is running / closed.

 public void onMessageReceived(RemoteMessage remoteMessage) {

    session = new Session(this);
  //  if (session.getBscloggedin() || session.getAdploggedin()) {
       // Log.d(TAG, "FROM:" + remoteMessage.getFrom());

        //Check if the message contains data
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data: " + remoteMessage.getData());
        }

        //Check if the message contains notification

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Mesage body:" + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getBody());
        }
    }


/**
 * Dispay the notification
 * @param body
 */


private void sendNotification(String body) {

    //for CS101 announcement notification
    if (body.contains("CS101")) {
        Intent intent = new Intent(this, CS101noti.class);
        intent.putExtra("body", body);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/*Request code*/, intent, 0);
        //Set sound of notifica tion
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("mine")
                .setContentText(body)
                .setAutoCancel(true)
                .setSound(notificationSound)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0 /*ID of notification*/, notifiBuilder.build());
    }

Solution

  • onMessageReceived callback is not called when you receive notification messages in background. If you receive this type of message in background, you can only handle that in a launcher activity. enter image description here

    The solution would be to either change the backend so that it sends only data messages and you handle them internally, or write some routing code inside your launcher activity.