I have been using Notification
s for a while, and yesterday I noticed that the documentation of PendingIntent
says that the Intent that is passed to the PendingIntent.getActivity()
method must have the FLAG_ACTIVITY_NEW_TASK
set:
Note that the activity will be started outside of the context of an existing activity, so you must use the Intent.FLAG_ACTIVITY_NEW_TASK launch flag in the Intent.
However, I have never set this flag when using Notification
s, and yet so far I have not experienced any problem. I have seen out there several examples of Notification
s where the FLAG_ACTIVITY_NEW_TASK
is not set for the Intent
that the PendingIntent
is referencing. In particular, the official guide shows the snippet below:
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
And as you can see, they are not setting the FLAG_ACTIVITY_NEW_TASK
flag. So my question is, should I always set the FLAG_ACTIVITY_NEW_TASK
flag when using PendingIntent.getActivity()
, or are there some scenarios in which it can be omitted? In particular, when using Notification
s, can I use an Intent without setting this flag?
I believe the system sets it for you for notifications. You will get a new task when launched from a notification.
Yes, you should use FLAG_ACTIVITY_NEW_TASK
. Otherwise you may get unexpected behavior on some devices.
As of today (March 25, 2017) the official guide linked in the question has this updated code snippet:
// Creates an Intent for the Activity
Intent notifyIntent =
new Intent(this, ResultActivity.class);
// Sets the Activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
PendingIntent notifyPendingIntent =
PendingIntent.getActivity(
this,
0,
notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With