How do I open different activities when receiving

2019-09-24 07:53发布

问题:

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 page, it still opens main activity. What I want is if I receive a notification regarding Chat it should open chat activity and if regarding comments it should open comments activity and so on... Please help thanks.

回答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:

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


回答2:

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.



回答3:

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