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

后端 未结 8 1399
没有蜡笔的小新
没有蜡笔的小新 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:23

    Yes you can demand only one instance of these activities be created, but it is generally not recommended. If you simply are concerned about history, take a look at Intent.FLAG_ACTIVITY_CLEAR_TOP.

    0 讨论(0)
  • 2020-12-08 07:25

    This is your flag! http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_REORDER_TO_FRONT

    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
    

    Note the 'addFlags'. Also note that, onCreate will not be called on this Activity when a new Intent is delivered to it. It will be delivered via the onNewIntent().

    This does not ensure that there is a single instance of the Activity running. To ensure that, check this out: http://developer.android.com/guide/topics/manifest/activity-element.html#lmode

    0 讨论(0)
  • 2020-12-08 07:30

    in Manifest Activity property you can give this parameter android:launchMode="singleInstance"

    Read in more detail here http://developer.android.com/guide/topics/manifest/activity-element.html

    0 讨论(0)
  • 2020-12-08 07:32

    Add intent Flags as

    Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP); StartActivity(srcActivity.java, DesiredActivity.class);

    Then at onPause() DesiredActivity

    Add finish(), This did the work for me.

    0 讨论(0)
  • 2020-12-08 07:34

    This worked for me.

    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.

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题