Is there any way to have one and only one instance of each activity?

后端 未结 8 1432
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 06:41

I\'m finding that in my application, the user can get quite \'nested\' in the various activities that are opened while the user is using the application.

For example

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 07:34

    I wanted to have only one Instance of MainActivity, but when I add:

    launchMode="singleInstance"
    

    to my manifest a white screen appears before all of my app activities, so I removed singleInstance code from manifest. I added two public static variable of my MainActivity to MainActivity Class:

    public static MainActivity mainActivity_instance = null;
    public static MainActivity mainActivity_OldInstance = null;
    

    then I added the following code to onCreate():

     if(mainActivity_instance != null)//if true, it means there was an instance of mainActivity before and it had to be closed.
            mainActivity_OldInstance = mainActivity_instance;
        mainActivity_instance = this;
     if(mainActivity_OldInstance != null)
            mainActivity_OldInstance.finish();
    

    As you see, I finished previous instance of MainActivity just as the new Instance created!

提交回复
热议问题