Reputation: 42760
I was wondering, what is the difference between the 2 code?
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.
If set, the activity will not be launched if it is already running at the top of the history stack.
My understanding is
FLAG_ACTIVITY_CLEAR_TOP
- Clear all activities on the top, and prevent more than 1 instance of same Activity within a same task stack.FLAG_ACTIVITY_SINGLE_TOP
- Prevent more than 1 instance of same Activity within a same task stack.If my understanding is correct, isn't Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
seems redundant?
Can we just write Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
?
Upvotes: 4
Views: 1330
Reputation: 943
FLAG_ACTIVITY_CLEAR_TOP
will create a new Activity and close the others on top.
FLAG_ACTIVITY_SINGLE_TOP
will just open/re-open that activity, depending if that was already launched.
The new intent will be received at onNewIntent
method, in both cases but the first will destroy other activities. We'll need to imagine that there is a stack.
That stack is formed by the order you've started the activities. Think in that scenario. Start Activity A, then start Activity B and then Activity C
The stack would be like that:
_ Activity C
_ Activity B
_ Activity A
Then if you start Activity A whith FLAG_ACTIVITY_CLEAR_TOP
, all activities on top of Activity A will be closed, and the intent will be delivered onNewIntent
.
Upvotes: 1
Reputation: 781
It depends on what you have in other parts of your code. If the only place where you call startactivity is the one you posted, yes the Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP is redundant.
But if you have the same activity launched from another piece of code, this may be not redundant. It all depends on what you have on the activity stack in this moment.
Upvotes: 0