Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep only one instance of each activity in entire app

I want to keep a single instance of every Activity I start in my application. The launchMode singleTask was an option but it is working for only one Activity.

I want

  • to start an Activity if there is no instance and it is called.
  • and if any other instance of that Activity is present already then that instance will brought to front without creating a new instance of that Activity.
  • This property will be applied to more than one Activity.
  • No Activity does guarantee that it will be always on the top of the history stack.

My work until now:

I got many suggestions which are not valid for my case, so I want to point these out so that no other person would give the same suggestion.

  • I have set the launchMode to singleTop and this works only if the Activity is at the top of the history stack. onNewIntent() only gets called if Activity is at the top of history stack. and in my case the Activity may be at any position in stack. So this is not working.
like image 529
Sagar Nayak Avatar asked Apr 25 '16 12:04

Sagar Nayak


2 Answers

When you launch an Activity, do it like this:

Intent intent = new Intent(this, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

If an instance of this Activity already exists, then it will be moved to the front. If an instance does NOT exist, a new instance will be created.

like image 175
David Wasser Avatar answered Sep 23 '22 16:09

David Wasser


You can set the android:launchMode of your activity to singleTop In this case the if the activity already exists, new intents will bring it to front will be delivered to the activity's onNewIntent() http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

This will work if your activity is on the top of the stack.

if you want to have a single instance of the activity, then you can set your launchMode to singleTask, but this is not recommended as it will make your activity reside in a separate task , which can be confusing to the users.

like image 21
Mina Wissa Avatar answered Sep 22 '22 16:09

Mina Wissa