5

I try to execute a function in my MainActivity when a notification is clicked. The function needs a data that I put in intent extras.

The problem is when I click the notification when the application is running the function is executed, but when I click the notification when the application is in the background, the function isn't executed. I've checked it and it's because the data that I put in intent extras is empty when the application is in the background.

How can I solve this problem? Thanks!

This is the response i receive :

{
    "to":"blablabla",
    "notification": {
        "body":"Sentiment Negative from customer",
        "title":"Mokita"
    },
    "data" : {
        "room_id":1516333
    }
}

This is my notification code :

public void onMessageReceived(RemoteMessage message) {
    super.onMessageReceived(message);
    Log.d("msg", "onMessageReceived: " + message.getData().get("room_id"));
    String roomId = message.getData().get("room_id");

    Intent intent = new Intent(this, HomePageTabActivity.class);
    intent.putExtra("fromNotification", true);
    intent.putExtra("roomId", roomId);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    String channelId = "Default";
    NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(message.getNotification().getTitle())
            .setContentText(message.getNotification().getBody())
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
        manager.createNotificationChannel(channel);
    }

    manager.notify(0, builder.build());
}

}

And this is the function and how i executed it in MainActivity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer);
    onNewIntent(getIntent());
}

@Override
    public void onNewIntent(Intent intent){
        Bundle extras = intent.getExtras();
        if(extras != null){
            if(extras.containsKey("fromNotification") || extras.containsKey("roomId")) {
                openChatRoom(Long.valueOf(extras.getString("roomId")));
            }else if(extras.containsKey("fromNotification") && extras.containsKey("roomId")){
                openChatRoom(Long.valueOf(extras.getString("roomId")));
            }else{
                Log.e("EXTRAS room",""+extras.getString("roomId"));
                Log.e("EXTRAS STATUS",""+extras.getBoolean("fromNotification"));
            }
        }else{
            Toast.makeText(HomePageTabActivity.this,"Empty",Toast.LENGTH_SHORT).show();
        }
    }


public void openChatRoom(long roomId){
        Log.d("LONG ROOM",""+roomId);
        QiscusRxExecutor.execute(QiscusApi.getInstance().getChatRoom(roomId),
        new QiscusRxExecutor.Listener<QiscusChatRoom>() {
            @Override
            public void onSuccess(QiscusChatRoom qiscusChatRoom) {
                startActivity(GroupRoomActivity.
                        generateIntent(HomePageTabActivity.this, qiscusChatRoom));
            }
            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
    }
Rifki Maulana
  • 133
  • 2
  • 13
  • 1
    1) Inside onNewIntent(Intent intent) must have 'this.setIntent(intent). 2) Add android:launchMode="singleTask" for HomePageTabActivity in Manifest. – Amad Yus Dec 19 '18 at 07:12
  • still not working when i click the notification when app is in background – Rifki Maulana Dec 19 '18 at 07:31
  • I change the response to this : { "to":"blabalasd", "data":{ "title":"Your title", "body":"Your message", "room_id":1516333 } } and it's working now – Rifki Maulana Dec 19 '18 at 07:38

3 Answers3

5

Firebase has two types of messages: notification messages and data messages. If you want FCM SDK to handle the messages by its own, you need to use notification. When the app is inactive, FCM will use notification body to display the messages. In this state, onMessageReceived also will not be triggered. If you want app to process the messages, you need to use data. You might need to change push notification payload from

{
   "message":{
   "token":"xxxxx:...",
   "notification":{
          "title":"Your title",
          "body":"Your message"
      }
   }
}

to

{
   "message":{
   "token":"xxxxx:...",
   "data":{
          "title":"Your title",
          "body":"Your message",
          "fromNotification":"true",
          "roomId":"123"
      }
   }
}

You also need to process the messages in onMessageReceived(RemoteMessage remoteMessage) accordingly. You can read about notification behaviour in Notifications and data messages.

Amad Yus
  • 2,856
  • 1
  • 24
  • 32
  • I've editted the question and add the response i get from FCM, and complete code of my notification. Could you take a look and tell me where i did wrong ? – Rifki Maulana Dec 19 '18 at 05:34
  • not receiving `getExtras` in `LauncherActivity` when app is in background ay help ? – Ahmad Mar 30 '20 at 08:00
2

these payloads will be delivered to the activity you are specifying in the pending intent. so when the user clicks on your notification, HomePageTabActivity launches and you can get the intent by calling getIntent() anywhere in activity lifecycle. but because you are setting singleTop flag on activity if HomePageTabActivity is already launched, Android will not launch it again and will pass the new Intent (provided in notification) to onNewIntent() instead. you can consume it there or even call the getIntent() to get the new value from there on.

seyed Jafari
  • 1,235
  • 10
  • 20
  • I've editted the question and add the response i get from FCM, and complete code of my notification. Could you take a look and tell me where i did wrong ? – Rifki Maulana Dec 19 '18 at 05:35
1

Receive messages in an Android app. Messages with both notification and data payload, both background and foreground. In this case the data payload is delivered to extras of the intent of your launcher activity. If you want to get it on some other activity, you have to define click_action on the data payload. So get the intent extra in your launcher activity.

aslamhossin
  • 1,217
  • 12
  • 22
  • I've editted the question and add the response i get from FCM, and complete code of my notification. Could you take a look and tell me where i did wrong ? – Rifki Maulana Dec 19 '18 at 05:35
  • Is it HomePageTabActivity.class your Launcher Activity? You can only get extras from your launcher activity. So if you want to get message from background outside the launcher activity then send extras into your launcher activity. After getting extras from launcher you can send it your desire activity from your launcher activity. Note: you can get extras only from launcher activity cause data stay in system blob which is not accessible from others activity. Can read sample https://github.com/firebase/quickstart-android – aslamhossin Dec 19 '18 at 05:51
  • With launcher activity do you mean the activity that runs first when app is being opened ? if i have a SplashScreen as my launcher activity, should i put SplashScreen.java in the pending intent and put the extras there? – Rifki Maulana Dec 19 '18 at 06:58
  • Yes, you have to put extras into launcher activity (SplashScreen). – aslamhossin Dec 19 '18 at 07:01
  • its working now, i changed the response to this { "to":"blalalal", "data":{ "title":"Your title", "body":"Your message", "room_id":1516333 } } Thanks for your time :) – Rifki Maulana Dec 19 '18 at 07:42