I have an app that I have running a media player and I want to resume the activity from my apps home activity.
I can successfully do this by adding the following flags to the startActivity Call:
myIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
I am worried that this is not an ideal way to do things since it took me a long time to find it. It made me think that no one uses it very much.
Are there any pitfalls to using this method?
Just to make sure I understand your question correctly: Say your activity stack is something like A -> B -> C, and now from C you want to clear the stack and get back to A.
If this is what you want, then those intent flags are correct and should work as expected, as per the Android-developer docs.
I know that this question is quite older and may you have solved your problem and may be travelled to mars and back in those years.But just to make things clear for the people coming here and looking for an explanation:
According to Official Documentation:
If set, the activity will not be launched if it is already running at the top of the history stack.
- Suppose you have BackStack of
A-B-C-D
and You have launched
another intent Starting Activity A
with FLAG_ACTIVITY_CLEAR_TOP
at this point what android will be do is Simply Clear All the
Activities on the Top of Activity A
, means now your BackStack Will
Look like-> A
(yes that's it because you have cleared all the
activities on top of it).
- And In Second Scenario Suppose You have the same BackStack A-B-C-D
and you launched an Intent Starting Activity A with
FLAG_ACTIVITY_SINGLE_TOP, now your BackStack will look like->
A-B-C-D-A (Confused? Don't Worry Next Example Will Clear All Your
Confusions)
Third Scenario, We start with the same BackStack A-B-C-D
and We
will launch an Intent Starting Activity D
with
FLAG_ACTIVITY_SINGLE_TOP
, now our BackStack will look like->
A-B-C-D
(Yes the BackStack remains in the Same Order because our
FLAG prohibits the launch Same Activity If it is the Currently on Top
of the Stack and Showing on the User screen.
Last Scenario, We start with our same BackStack A-B-C-D
and We will
launch an Intent Starting Activity D
but this time with no FLAGS,
now our BackStack will look like-> A-B-C-D-D
.
Got it? FLAG_ACTIVITY_SINGLE_TOP
is only useful When you are
starting the Same Activity Which is Currently Showing On the Screen
and You want to prohibit the launch new Instance of the Existing Activity.