Android Notification: Requires Intent.FLAG_ACTIVITY_NEW_TASK?
In the class document Notification
I see the following:
public PendingIntent contentIntent
Execution target when extended status record is clicked. If this is an action, it must include a flag
FLAG_ACTIVITY_NEW_TASK
that requires you to take care of task management, as described in the Tasks and Back Stack document. In particular, be sure to read the Notifications Handling section for the correct ways to launch an application from a notification.
I have read the materials related to the above, but I still don't understand. Why is a flag FLAG_ACTIVITY_NEW_TASK
required when an action should be started when a notification is clicked? I tried the following code:
NotificationManager manager = (NotificationManager)context.
getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(
android.R.drawable.stat_notify_sync, title,
System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(context, NotifiedActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // IS THIS REALLY REQUIRED??
PendingIntent pt = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, title, text, pt);
manager.notify(0, notification);
I ran the above code with intent.setFlags
and without a line and there seems to be no difference. In fact, a lot of the code samples I've found just don't have this line. So why does the doc say the flag FLAG_ACTIVITY_NEW_TASK
is required, and what's the difference in handling notifications?
source to share
This flag is technically required. But since it's required, Android will be nice and just install it for you; -)
The reason why this is required is as follows:
The code that processes Notification
and calls startActivity()
to actually run Intent
does not work in the "task". This is the system code entering the system Notification
. Typically, if you invoke startActivity()
and the flag is Intent.FLAG_ACTIVITY_NEW_TASK
not set , Android will try to run that activity on the current task (that is: the task containing the activity that invokes startActivity()
). Since it is not a task in this case , Android should start the Activity in another task. Therefore, you need to specify Intent.FLAG_ACTIVITY_NEW_TASK
.
In practice, this does not always create a new task as Android will first try to find a (suitable) existing task to launch the Activity in. If your app is already running, Android will simply launch an Activity on this task. (This is not 100% true, there are other special cases that can change this logic, but I will not cover them here).
NOTE. The same situation exists if you call startActivity()
from Service
or BroadcastReceiver
. In this case, the flag Intent.FLAG_ACTIVITY_NEW_TASK
must be set because there is no current task, so Android must start the Activity in another task.
source to share