android - Firebase Cloud Message Notification Opens MainActivity Instead of Target NotificationActivity - Stack Overflow

I am trying to open NotificationActivity when a user taps on a notification created by Firebase Cloud M

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.

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.

Share Improve this question asked Nov 19, 2024 at 14:02 AmanAman 2,4413 gold badges21 silver badges25 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 0

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.

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 fet to use loader and smooth transition, it will generate good effect

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745556402a4632846.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信