Home » Android » android – How to check if an activity is the last one in the activity stack for an application?

android – How to check if an activity is the last one in the activity stack for an application?

Posted by: admin March 11, 2020 Leave a comment

Questions:

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

How to&Answers:

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

Answer:

I’m going to post the comment of @H9kDroid as the best answer here for people that have a similar question.

You can use isTaskRoot() to know whether the activity is the root of a task.

I hope this helps

Answer:

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

Answer:

Hope this will help new beginners, Based above answers which works for me fine, i am also sharing code snippet so it will be easy to implement.

solution : i used isTaskRoot() which return true if current activity is only activity in your stack and other than i also handle case in which if i have some activity in stack go to last activity in stack instead of opening new custom one.

In your activity

   @Override
    public void onBackPressed() {

        if(isTaskRoot()){
            startActivity(new Intent(currentActivityName.this,ActivityNameYouWantToOpen.class));
            // using finish() is optional, use it if you do not want to keep currentActivity in stack
            finish();
        }else{
            super.onBackPressed();
        }

    }

Answer:

One way to keep track of this is to include a marker when you start a new activity and check if the marker exists.

Whenever you start a new activity, insert the marker:

newIntent=new Intent(this, NextOne.class);
newIntent.putExtra(this.getPackageName()+"myself", 0);
startActivity(newIntent);

And you can then check for it like this:

boolean islast=!getIntent().hasExtra(this.getPackageName()+"myself")

Answer:

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.

Answer:

The Problem with sandrstar’s solution using ActivityManager is: you need a permission to get the tasks this way.
I found a better way:

getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)

The Activity on the Stack bottom should allways get this category by default while other Activities should not get it.
But even if this fails on some devices you can set it while starting your Activity:

Intent intent = new Intent(startingActivity, SomeActivityClass.class);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
activity.startActivity(intent);

Answer:

I’ve created a base class for all my activities, extending the AppCompatActivity, and which has a static counter:

public abstract class BasicActivity extends AppCompatActivity {
    private static int activityCounter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ++activityCounter;
        ...
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        --activityCounter;
        if(activityCounter==0) {
            // Last instance code...
        }
    }

    public boolean isLastInstance() { return (activityCounter==1); }
}

This has worked well enough, so far; and regardless of API version. It requires of course that all activities extends this base class – which they do, in my case.

Edit: I’ve noticed one instance when the counter goes down to zero before the app completely exits, which is when the orientation is changed and only one activity is open. When the orientation changes, the activity is closed and another is created, so onDestroyed is called for the last activity, and then onCreate is called when the same activity is created with the changed orientation. This behaviour must be accounted for; OrientationEventListener could possibly be used.

Answer:

Android implements an Activity stack, I suggest you read about it here. It looks like all you want to do though is retrieve the calling activity: getCallingActivity(). If the current activity is the first activity in your application and the application was launched from the home screen it should (I assume) return null.

Answer:

The one thing that missed here, is the “Home key” click, when activated, you can’t detect this from your activity, so it would better to control activity stack programmatically with handling “Back key” press and moving to required activity or just doing necessary steps.

In addition, you can’t be sure, that starting your activity from “Recent Activity” list can be detected with presetting some extra data into intent for opening activity, as it being reused in that case.