Aman
Aman

Reputation: 2411

Firebase Cloud Message Notification Opens MainActivity Instead of Target NotificationActivity

I am trying to open NotificationActivity when a user taps on a notification created by Firebase Cloud Messaging (FCM). However, the app always launches the MainActivity instead of the desired NotificationActivity.

When I create a notification through a button click in the app, it correctly opens NotificationActivity. But when the notification is generated by FCM (via MyFirebaseMessagingService), tapping on the notification opens the MainActivity instead.

Here are the relevant parts of my code and configuration:

1. Firebase Messaging Service

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getNotification() != null) {
            showNotification(
                getApplicationContext(),
                remoteMessage.getNotification().getTitle(),
                remoteMessage.getNotification().getBody()
            );
        }
    }

    public static void showNotification(Context context, String title, String message) {
        String channelId = "general";

        Intent intent = new Intent(context, NotificationActivity.class);
        intent.setAction("OPEN_NOTIFICATION_ACTIVITY");
        intent.putExtra("notification_title", title);
        intent.putExtra("notification_body", message);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                0,
                intent,
                PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
        );

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true);

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    channelId, "General", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(1, mBuilder.build());
    }
}

2. Here is my AndroidManifest.xml configuration:

<service
    android:name=".service.MyFirebaseMessagingService"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

<activity
    android:name=".NotificationActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="OPEN_NOTIFICATION_ACTIVITY" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

<activity
    android:name=".MainActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

3. Observations

Expected Behavior: When tapping the notification, NotificationActivity should open, displaying the title and body passed in the Intent.

Actual Behavior: MainActivity opens instead of NotificationActivity.

Upvotes: 0

Views: 169

Answers (3)

Mamoon Asad
Mamoon Asad

Reputation: 64

If the fcm message have both notification object and data object, and your app is in background then the android system will auto generate notification and will not trigger onMessageReceived.

Now when you click on the notification, app launcher activity will be called (this is the default behavior and probably happening in your case).

If you want onMessageReceived to trigger every time (even when your app is in kill state) then remove notification object and send only data object in your fcm message.

You would also have to change NotificationActivity to launcher because if your app is in kill state then you can only open launcher activities.

I would suggest to open your MainActivity but pass flags in intent extras so you can detect specific usecase in which you have to open NotificationActivity

Upvotes: 0

Ahmad Jawad
Ahmad Jawad

Reputation: 1

You posted a job on upwork, but i didn't have connects to submit the proposal , so I'm giving you a Work arround , you can simple put some extras while opening the Main Activity and listen that extra in main Activty like in MyFirebaseMessagingService

 `putExtra("type", data["notification"])`

and on MainActivity

  intent?.extras?.let { extras ->
            val type = extras.getString("type")
    if(type=="notification"){
//Open Notification activty
}
}

don't forget to use loader and smooth transition, it will generate good effect

Upvotes: 0

Vansh Patel
Vansh Patel

Reputation: 342

The problem is that, when your application is in background or closed, the Firebase automatically creates notification and onMessageReceived is not called at all. As you have said that the notification opens desired activity when showed by button click, at that time, the notification is created by you and you have specifically written to open NotificationActivity. Now, when Firebase creates notifications, it opens the MainActivity only.

How to fix:

Pass click_action along with Firebase message like this:

{
    "to": "some_device_token",
    "notification": {
        "title": "hello",
        "body": "yo",
        "click_action": "OPEN_NOTIFICATION_ACTIVITY" // for intent filter in your activity
    },

    "data": {
        "extra": "extra data here..."
    }
}

Hope this helps.

Upvotes: 0

Related Questions