Android Notification PendingIntent Extras null
I just got the answer,
add line: resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
NOTICE: if you add it as resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
It won't work.
I also tried other flags like, "FLAG_ACTIVITY_NEW_TASK" and "FLAG_ACTIVITY_RESET_TASK_IF_NEEDED". neither works here.
For me, in addition to setting Intent.FLAG_ACTIVITY_SINGLE_TOP , I had to add a unique action to the intent:
Intent resultIntent = new Intent(caller, NotificationActivity.class);
String xId = getNextUniqueId();
resultIntent.putExtra("x_id", xId);
resultIntent.setAction(xId);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
.. without the setAction(..), Extras is null on the Intent received by my NotificationActivity.
This post helps explain it: https://stackoverflow.com/a/3128271/2162226
When an activity is launched(when it is first started ) or relaunched(when it's brought to the top of the stack) the getIntent().getExtra()
won't give null
. But when the activity is present on the top of the stack then on starting that activity with the use of PendingIntent
would not relaunch the activity(onCreate()
won't get called) instead onResume()
would be called. And getIntent().getExtra()
would return the value which is associated with the intent that started the activity(which is null
).
In order to update the intent do the following steps:
1). Set FLAG_ACTIVITY_SINGLE_TOP
and FLAG_ACTIVITY_CLEAR_TOP
flags in your intent.
resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
2). Override onNewIntent()
in the activity where getIntent().getExtra()
is called. This method is called by FLAG_ACTIVITY_SINGLE_TOP
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
For more info: See this doc
in PendingIntent use this flag PendingIntent.FLAG_UPDATE_CURRENT
it's work for me
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);