简体   繁体   中英

How to check for existing activities when back button pressed

Generally, when the back button is clicked, I call finish() , and I am taken back to the previous activity (which is my MenuActivity) :

@Override
public void onBackPressed() {

    finish();

}

However, sometimes the there are no other activities running when the back button is clicked and the app simply exits. Is there a way I can check if an activity exists or is running in the background/in onPause state etc...

I would like to write something like this:

@Override
public void onBackPressed() {

    if(isActivitiesInStack) //if there are still activities in stack

        finish(); //simply call finish and be taken back to next activity

    else { // else, there are no acitivites in the stack

        Intent intent = new Intent(ThisActivity.this, MenuActivity.class); // then create an intent and send me to the menu acitivy
        startActivity(intent);
        finish()          
    }
}

If you know to which activity you want to go in onBackPressed() you can start the activity with the FLAG_ACTIVITY_CLEAR_TOP . It would switch to the instance of MenuActivity if an instance is existing, but it would also remove all activity instances which are between your current activity instance and the MenuActivity instance. In the other case it would just start a new instance.

Intent intent = new Intent(context, MenuActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

I think, it may be helpful to you

public boolean isRunning(Context ctx) {
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

    for (RunningTaskInfo task : tasks) {
        if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName())) 
            return true;                                  
    }

    return false;
}

Anyhow this method has been deprecated from Android API 21 (Lollipop)

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