如何检查,如果一个活动是最后一个在一个应用程序的活动栈? [英] How to check if an activity is the last one in the activity stack for an application?
问题描述
我想知道,如果用户将返回到主屏幕,如果他退出当前的活动。
I want to know if user would return to the home screen if he exit the current activity.
推荐答案
有可能来检查使用当前的工作和他们的筹码<一href="http://developer.android.com/reference/android/app/ActivityManager.html#getRunningTasks%28int%29"相对=nofollow> ActivityManager 。
There's possibility to check current tasks and their stack using ActivityManager.
因此,要确定一项活动是最后一个:
So, to determine if an activity is the last one:
-
在清单
- 请求android.permission.GET_TASKS权限。
-
使用下面的code:
- request android.permission.GET_TASKS permissions in the manifest.
Use the following code:
ActivityManager mngr = (ActivityManager) getSystemService( ACTIVITY_SERVICE );
List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10);
if(taskList.get(0).numActivities == 1 &&
taskList.get(0).topActivity.getClassName().equals(this.getClass().getName())) {
Log.i(TAG, "This is last activity in the stack");
}
请注意,上面code有效期只有当你有一个任务。如果有可能的一些任务将存在于您的应用程序 - 你需要检查其他的任务列表的元素。了解更多关于任务任务和返回堆栈
Please note, that above code will be valid only if You have single task. If there's possibility that number of tasks will exist for Your application - You'll need to check other taskList elements. Read more about tasks Tasks and Back Stack
更新(2015年7月):
由于<一href="http://developer.android.com/reference/android/app/ActivityManager.html#getRunningTasks%28int%29"相对=nofollow> getRunningTasks()得到德precated,从API 21,最好遵循 raukodraug 的答案或埃德伯内特 之一(我会preFER第二个)。
Since getRunningTasks() get deprecated, from API 21 it's better to follow raukodraug answer or Ed Burnette one (I would prefer second one).
这篇关于如何检查,如果一个活动是最后一个在一个应用程序的活动栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!