Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find whether activity is last activity in stack

I am opening a link in my app and once back is pressed I want to show HomePage to retain user for some more time. I have been trying to acheive this but unable to do so. I get homeLauncher activity as my top as well as baseActivity.

DeepLink Tap > Open desired Activity > user presses back button > Check if its last activity but not homeActivity > If yes, Navigate user to homeActivity.

Tried following code:

@Override
public void onBackPressed() {
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())){
  //// This is last activity
}
else{
    //// There are more activities in stack
}

super.onBackPressed();
}

Android Studio Evalation

I have also tried isTaskRoot but result is same. It doesn't give right answer.Please help

like image 559
user1288005 Avatar asked Nov 19 '15 10:11

user1288005


2 Answers

Use isTaskRoot() method. (From a h9kdroid comment - here)

@Override
public void onBackPressed() {
   ActivityManager mngr = (ActivityManager) getSystemService( ACTIVITY_SERVICE );
   List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10);

   if(isTaskRoot()){
     //// This is last activity
   } else{
     //// There are more activities in stack
   }

   super.onBackPressed();
}
like image 191
anthorlop Avatar answered Oct 08 '22 22:10

anthorlop


You could simply use the ActivityManager it keeps track of which activity is and is not here is a piece of code I stumbled on that I use always:

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");
}
like image 1
life evader Avatar answered Oct 08 '22 23:10

life evader