Jack Stern Jack Stern - 20 days ago 11
Android Question

Android 2nd Push Notification Payload Data Not Receiving In Extras When App is In Background

I'm facing a very weird problem of not receiving payload data second time when the app is in background.

For ex - (When I had not started my app yet)


  • When I receives notification for the first time it will open my app and read the extras from the notification.

  • When I receive the second notification it maximises my app or bring my app to the front but does not read the extras.



When my app is open everything works fine. Even when I put my app on background after manually opening it then also all notifications work fine.

Here is my manifest code

<activity
android:name=".PagerActivity"
android:launchMode="standard">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>


Here is my activity code

@Override
public void onNewIntent(Intent newIntent) {
this.setIntent(newIntent);

// Now getIntent() returns the updated Intent
if(getIntent().hasExtra("sno")){
Log.d("New Intent DATA", "Yes it has the data sno is: " + getIntent().getExtras().getString("sno"));
}


}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getIntent().hasExtra("sno")){
Log.d("DATA", "Yes it has the data");
}
}


I tried researching a lot but to no avail. Please let me know if you need any other details.

I'm using firebase to send notification with custom data. I also tried it sending via web server but still didn't got it working.

I debugged my app and found that when I'm opening my app through second notification new instance is not being created.

Answer

When you send both notification and data payload and if your app is in background, notification will be shown in the tray, but on clicking the notification if your launching activity is in background, it will be brought to foreground and you will not receive data payload.

One solution is to set the launch mode of that specific actvitiy to singleTask and implement onNewIntent in the activity to receive data payload.

In this way, your activity will be brought to foreground and activities residing on the top of this activity in the stack will be destroyed.

You can find more about launch modes here.

I am not sure weather its a best solution or not but I just got this solution in my mind.