Skip to content Skip to sidebar Skip to footer

How Do I Open Different Activities When Receiving Notification From Firebase

In my app there are different categories, a main page(MainActivity), comments activities and Chat activity etc. When i receive a notification, either from comments, Chat or main pa

Solution 1:

In your message notification data, add property click_action with value of an action string. For the activity you want to start, update your manifest to define an intent filter that matches the action.

For example, with message:

{
  "to": "dhVgCGVkTSR:APA91b...mWsm3t3tl814l",
  "notification": {
    "title": "New FCM Message",
    "body": "Hello World!",
    "click_action": "com.example.FCM_NOTIFICATION"
  },
  "data": {
    "score": "123"
  }
}

Define the intent filter like this:

<activityandroid:name=".MyFcmNotificationActivity"><intent-filter><actionandroid:name="com.example.FCM_NOTIFICATION" /><categoryandroid:name="android.intent.category.DEFAULT" /></intent-filter></activity>

Solution 2:

The answer to your question is PendingIntent. You will need to send in the FCM payload the type of notification (chat, comments etc.,) and then in your onMessageReceived() you process the notification, know the type and create a PendingIntent using the desired activity. When users clicks on the notification, android will launch the activity specified in the PendingIntent. Refer to this android documentation. I hope this helps.

[Update] I like Bob's answer better but I've never tried it myself

Solution 3:

In your MainActivity onCreate() you need to get the intent that started the activity and retraive the data from notification.

    Bundle bundle = getIntent().getExtras();
    if (bundle != null && bundle.get("data")!=null) {
        //here can get notification message
        String datas = bundle.get("data").toString();
    }

From here you can redirect the user depending on data you received from notification. https://firebase.google.com/docs/cloud-messaging/android/receive#backgrounded

Handle notification messages in a backgrounded app

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.

This includes messages that contain both notification and data payload (and all messages sent from the Notifications console). In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

Post a Comment for "How Do I Open Different Activities When Receiving Notification From Firebase"