[英]How to check for existing activities when back button pressed
通常,当单击后退按钮时,我调用finish()
,然后将我带回到上一个activity
(这是我的MenuActivity):
@Override
public void onBackPressed() {
finish();
}
但是,有时,当单击后退按钮并且应用程序退出时,没有其他activities
运行。 有没有一种方法可以检查activity
存在或正在后台运行/处于onPause
状态等...
我想写这样的东西:
@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()
}
}
如果你知道你想要哪个活动中去onBackPressed()
就可以开始与活动FLAG_ACTIVITY_CLEAR_TOP
。 如果存在实例,它将切换到MenuActivity
实例,但是它也将删除当前活动实例和MenuActivity
实例之间的所有活动实例。 在其他情况下,它将仅启动一个新实例。
Intent intent = new Intent(context, MenuActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
我认为这可能对您有帮助
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;
}
无论如何,此方法已从Android API 21(Lollipop)中弃用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.