How to check if an activity is the last one in the

2019-01-03 23:22发布

I want to know if user would return to the home screen if he exit the current activity.

9条回答
孤傲高冷的网名
2楼-- · 2019-01-04 00:05

UPDATE (Jul 2015):

Since getRunningTasks() get deprecated, from API 21 it's better to follow raukodraug answer or Ed Burnette one (I would prefer second one).


There's possibility to check current tasks and their stack using ActivityManager.

So, to determine if an activity is the last one:

  • 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");
    }
    

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


查看更多
对你真心纯属浪费
3楼-- · 2019-01-04 00:07

While there may be a way to achieve this (see other answers) I would suggest that you shouldn't do that. Normal Android applications shouldn't need to know if the Home screen is about to display or not.

If you're trying to save data, put the data saving code in your onPause() method. If you're trying to give the user a way to change their mind about existing the application, you could intercept the key up/down for the Back key and the onBackPressed() method and present them with an "Are you sure?" prompt.

查看更多
SAY GOODBYE
4楼-- · 2019-01-04 00:12

there is an easiest solution to this, you can use isTaskRoot() in your activity

查看更多
登录 后发表回答