Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use FLAG_ACTIVITY_NEW_TASK in a Notification's PendingIntent?

I have been using Notifications 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 Notifications, and yet so far I have not experienced any problem. I have seen out there several examples of Notifications 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 Notifications, can I use an Intent without setting this flag?

like image 869
odracirnumira Avatar asked Aug 17 '12 06:08

odracirnumira


2 Answers

I believe the system sets it for you for notifications. You will get a new task when launched from a notification.

like image 55
Philip Pearl Avatar answered Sep 27 '22 02:09

Philip Pearl


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
);
like image 35
TalkLittle Avatar answered Sep 24 '22 02:09

TalkLittle