Android starting existing app instance from Widget
-
16-06-2021 - |
Question
I have an app that contains several activities...so lets say user is navigating activity stack A->B->C. Then presses the HOME button. Now when the user clicks on the Widget, I just want bring my app's existing/current instance to the foreground. I do NOT want a new instance of the app. I want activity C to get back to foreground.
I tried launchMode to "singleTask" | "singleInstance"
but that does NOT solve my desired requirement since it clears the current instance and creates a new one with activity A.
Any ideas how to solve this?
Thanks much!
Solution 2
I managed to figure out a solution. I set the specialized launch mode....
android:launchMode="singleInstance"
Every time the user clicks on the widget or the app icon again, the default activity A is started. To open the app up where it last was, inside the onCreate()
method in your MainActivity
class just check isTaskRoot()
. If false, call finish()
and the activity A (MainActivity) will not appear and the app will open up to where it was in activity B.
OTHER TIPS
Using a "singleInstance
" is not such a good idea (for many reasons).
Here is a better way - from your widget intent handler:
Intent yourActivity = new Intent(context, YourActivity.class);
yourActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(yourActivity);
You don't need to add CLEAR_TOP
to recall activity C, but you need it if you want to bring A or B.
I am only posting because between some 10+ similar posts nobody actually pointed the correct way of doing it.
http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP - last paragraph.
Try adding this to your intent
intent.setFlags( Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);