Reputation: 11
I launch an activity with startActivityForResult()
and want to prevent multiple instances from being started at the top of activity stack. So I expect android:launchMode="singleTop"
to do its work, but for some reason the flag gets ignored.
After some investigations I managed to launch only one instance by adding FLAG_ACTIVITY_REORDER_TO_FRONT
to intent, but I would be grateful if someone could explain me the reason why "singleTop" doesn't work in such case. The code is very simple.
// Activity class
Intent intent = new Intent(this, DetailsActivity.class);
// multiple instances can be launched without this line
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityForResult(intent, REQUEST_CODE_DETAILS);
// AndroidManifest.xml
<activity
android:name=".DetailsActivity"
android:launchMode="singleTop"/>
Upvotes: 1
Views: 2067
Reputation: 95578
The flag FLAG_ACTIVITY_SINGLE_TOP
must be ignored in this case because when you launch an Activity
using startActivityForResult()
you are basically saying that you want to launch an Activity
and have the Activity
return you a result.
If an instance of this Activity
already exists in the stack (regardless of where it is in the stack), that instance has not been setup to return a result to your Activity
. It is possible that that instance was launched using startActivity()
in which case it isn't setup to return a result at all. It could be that it was launched using startActivityForResult()
from another Activity
, in which case it is set up to return a result to the Activity
that launched it, not to your Activity
.
These 2 things: FLAG_ACTIVITY_SINGLE_TOP
and startActivityForResult()
therefore are in conflict.
Upvotes: 3
Reputation: 3394
How SingleTop work?
let suppose you have current activity stack like
A->B->C
Now from current activity C, if you start A activity which is a singleTop, so in this case system will create a new instance of A and brings that instance to top. (If specified activity is not on top then new instance will be created)
So stack will look like
A->B->C->A
Now if you try to open A again then in this case as A on top already, so NO new instance will be created. Instead A will receive callback in onNewIntent() method
Flag
FLAG_ACTIVITY_REORDER_TO_FRONT
it scans from the front of stack to back of stack and if it found instance of specified activity then brings that activity to front.
So in your case if DetailsActivity instacne is already present in system then this flag will bring DetailsActivity to front
Upvotes: 3