简体   繁体   中英

Get Singleton Instance of Android Activity?

I have an Android Activity. I want that this Activity is a Singleton. I did this by setting

android:launchMode="singleTop"

in my AndroidManifest.xml . Now I need a reference to this single Activity without starting it with an Intent.

I could create an instance like this:

MyActivity a = new MyActivity();

This would leads to a different instance than I would get when I do:

Intent intent = new Intent(context, MyActivity.class); 
startActivity(intent);

How do I get the same instance of my Activity as the Android system creates?

First you should be aware that you can not create an instance of activity by it's constructor and the only way is using intent to start it. The second point is the launch mode of activity that you should consider. singleTop means to bring the activity to top of the task not anymore and this doesn't mean that you have the same instance always, only if you have a created instance, android system use it instead of creating new activity in that stack. If you use singleTask the same instance will be used by system and the whole task containing the activity instance will be moved to top. And with a little different, the singleInstance launch mode means for system to use the same instance of activity in a single activity task and no other activity will be added to that task. And the default option is standard that after any intent to create the activity, it creates and launches a new instance of activity each time. I hope it was helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM