Android: How do I avoid starting activity which is already in stack?

前端 未结 7 2052
一整个雨季
一整个雨季 2020-12-23 12:20

Lets try to explain my question: I got an application and a service. The application is started with activity A. The service sends a broadcast that will let the application

相关标签:
7条回答
  • 2020-12-23 12:57

    Approaches android:launchMode="singleInstance" and just adding flags to the Intent do not work for me. What works is that:

    In the code where activity gets started:

    Intent intent = new Intent(activity, ActivityThatHasToBeStarted.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    startActivity(intent);
    

    In the ActivityThatHasToBeStarted:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        // Code for this creation
    }
    
    0 讨论(0)
  • 2020-12-23 13:00

    I think you need to make your activity B singleInstance that if it's already create you don't want to create again, that is launch mode of the activity can be defined in manifest android:launchMode that defines how the activity will be instanciated.

    in your case use android:launchMode="singleInstance"

    0 讨论(0)
  • 2020-12-23 13:01

    If the activity will be on the top if already started, set the FLAG_ACTIVITY_SINGLE_TOP flag

    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    mContext.startActivity(intent);
    
    0 讨论(0)
  • 2020-12-23 13:03

    You can use flag Intent.FLAG_ACTIVITY_NEW_TASK. If the activity is already running it will bring that to front instead of creating new activity.

    If you add Intent.FLAG_ACTIVITY_CLEAR_TOP with this, then all the activities after this activity in the backstack will be cleared.

    0 讨论(0)
  • 2020-12-23 13:03

    You may consider using android:launchMode="singleTop" instead of android:launchMode="singleInstance" Good article about the differences

    0 讨论(0)
  • 2020-12-23 13:14

    If you don't need the second activity anymore, it is good practise to finish it, then you should do this on the second activity after the operation is ended:

    startActivity(new Intent(this, FirstActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    finish();
    
    0 讨论(0)
提交回复
热议问题