I am trying to open an Activity
when the notification is clicked and below is my code.
Intent intent = new Intent(this.getApplicationContext(),
If you read the firebase docs in detail, there are two types of payloads
The data payload triggers the onMessageReceived() callback when app is both foreground and background. This is not the case with notification payload, which triggers the callback in only foreground state. So, if you use the data payload this problem should be solved.
I had the same problem in my app
This link helped me: https://developer.android.com/training/notify-user/navigation
What you need to do is define parent activity for your desired activity in Manifest:
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- MainActivity is the parent for ResultActivity -->
<activity
android:name=".ResultActivity"
android:parentActivityName=".MainActivity" />
And then use TaskStackBuilder in onMessageReceived method to create pending intent
// Create an Intent for the activity you want to start
Intent resultIntent = new Intent(this, ResultActivity.class);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
// Get the PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// then use this pending intent to build your notification
Thats the intented behaviour. If your app is in background, notification is created by android system which does not have your pendingIntent action.So it does not work. In the foreground case it works because notification is created by your code.
Please check the doc in the below link. https://firebase.google.com/docs/notifications/android/console-device#receive_and_handle_messages
Check this code and let me know.
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);