简体   繁体   English

按下后退按钮时如何检查现有活动

[英]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) : 通常,当单击后退按钮时,我调用finish() ,然后将我带回到上一个activity (这是我的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. 但是,有时,当单击后退按钮并且应用程序退出时,没有其他activities运行。 Is there a way I can check if an activity exists or is running in the background/in onPause state etc... 有没有一种方法可以检查activity存在或正在后台运行/处于onPause状态等...

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 . 如果你知道你想要哪个活动中去onBackPressed()就可以开始与活动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. 如果存在实例,它将切换到MenuActivity实例,但是它也将删除当前活动实例和MenuActivity实例之间的所有活动实例。 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) 无论如何,此方法已从Android API 21(Lollipop)中弃用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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