Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use both Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_SINGLE_TOP?

when a push notification is clicked I use something like that to initiate the intent I want:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
ctx.startActivity(intent);

It's part of code I've taken from a tutorial but I didn't really understand the use of both FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_SINGLE_TOP.

From the docs:

FLAG_ACTIVITY_NEW_TASK(Added in API level 1):

When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in.

FLAG_ACTIVITY_SINGLE_TOP(Added in API level 4):

If set, the activity will not be launched if it is already running at the top of the history stack.

Both sounds alike to me, I mean it sounds like the NEW_TASK makes sure that if your activity already exists within a task, then a new task won't be created but the old task appears(as I understand, can appear with different activity on top), SINGLE_TOP will only launch the activity if it's not at the top of the stack(so is it means that there will be 2 or more instances of the same activity)?

My question: Is there a difference between them that require the use of both?

like image 833
Aviel Fedida Avatar asked Aug 04 '16 11:08

Aviel Fedida


1 Answers

AFAIK

FLAG_ACTIVITY_SINGLE_TOP doesn't create a new task to launch itself. It always relies on the previous activity's task to launch itself (along with this, it does check if there is an instance already in the stack and show that if available. In either way, it doesn't create a new task)

where as

FLAG_ACTIVITY_NEW_TASK does create a new task unless there is a task with the same activity.

I know it kinda feels the same but the key difference here is when an activity is launched with FLAG_ACTIVITY_SINGLE_TOP for the FIRST TIME, it relies on existing task and FLAG_ACTIVITY_NEW_TASK creates a new task

like image 175
Cerlin Avatar answered Oct 21 '22 06:10

Cerlin