I have Activity A
with android:launchMode="singleTop"
in the manifest.
If I go to Activity B
, C
, and D
there I have menu shortcuts to return to my applications root activity (A
).
The code looks like this:
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
startActivity(myIntent);
However, instead of returning to the already existing instance A
of my MainActivity.class
it creates a new instance -> it goes to onCreate()
instead of onNewIntent()
.
This is not the expected behavior, right?
You can return to the same existing instance of Activity with
android:launchMode="singleInstance"
in the manifest. When you return to
A
fromB
, may be neededfinish()
to destroyB
.What actually worked for me in the end was this:
Firstly, Stack structure can be examined. For the launch mode:singleTop
If an instance of the same activity is already on top of the task stack, then this instance will be reused to respond to the intent.
All activities are hold in the stack("first in last out") so if your current activity is at the top of stack and if you define it in the manifest.file as singleTop
if you are in the ActivityA recreate the activity it will not enter onCreate will resume onNewIntent() and you can see by creating a notification Not:İf you do not implement onNewIntent(Intent) you will not get new intent.
This should do the trick.
When you create an intent to start the app use:
This is that should be needed.
Quote from the documentation:
I'm not 100% sure what "already has an existing instance of the activity at the top of its stack" means, but perhaps your activity isn't meeting this condition.
Would
singleTask
orsingleInstance
work for you? Or perhaps you could try settingFLAG_ACTIVITY_SINGLE_TOP
on the intent you are creating to see if that makes a difference, although I don't think it will.This is because the original A activity is already being destroyed by the time you start it from B, C or D. Therefore, onCreate will be called in stead of onNewIntent(). One way of solving this is to always destroy the existing A(using FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK conjunction when startActivity) before starting a new A, so onCreate will always be called, and you put the code of onNewIntent() into onCreate by checking if getIntent() is the intent you started with.