How to check if an activity is the last one in the activity stack for an application?
Solution 1
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
Solution 2
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
Solution 3
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();
}
}
Solution 4
there is an easiest solution to this, you can use isTaskRoot() in your activity
Solution 5
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")
virsir
Updated on March 29, 2020Comments
-
virsir about 4 years
I want to know if user would return to the home screen if he exit the current activity.
-
H9kDroid almost 13 yearsThat will not work since getCallingActivity() will return null if the activity was not started via startActivityForResult().
-
AlikElzin-kilaka about 11 yearsDoesn't work if the activity gets killed and the activity stack is reconstructed - each activity by demand.
-
Sufian about 10 yearsH9kDroid has made a correct suggestion. The selected answer is a hack. One should do it the right way using the
isTaskRoot()
method. -
sandrstar over 9 years@Sufian where is it hack particularly? The code is logical and uses open android APIs in the way they intended to be used (e.g. getRunningTasks should be used to get running tasks and one might want to call it only with the purpose to analyze these tasks). Usage of get(0) is well documented and logical 'Return a list of the tasks that are currently running, with the most recent being first and older ones after in order'.
-
Kaveesh Kanwal about 9 yearscan you please provide the single line of code so that its clear on how to use isTaskRoot. Thanks.
-
howettl about 9 years@TheHunter
if (isTaskRoot()) { // do something }
-
gilchris almost 9 yearsgetRunningTasks() is deprecated in API level 21.
-
Sagar Devanga over 8 yearsCan i do the same thing for fragments. If yes then how ? Please help
-
sandrstar over 8 years@SagarDevanga hm, probably you can try to use developer.android.com/reference/android/app/… , but it will require you to add every fragment to backstack. Otherwise, you can keep some kind of global counter of fragments in Application class for example.
-
Michael over 8 yearsHow about if I need a service running as long as the user hasn't left the activity? I can't trap any of the functions like onStop because these could be called after the screen is turned off.
-
chubbsondubs over 7 yearsThe only problem is that on <=4.4 I'm seeing it do different behavior than in >= 5.x. It seems to always return false.
-
Matt W about 7 yearsIf a background service launches an Activity, perhaps you'd like to know whether or not that's the only Activity on the stack.
-
nbtk over 6 yearsWhat if the activity is opened from push notification? They don't have the CATEGORY LAUNCHER
-
A. Binzxxxxxx over 6 yearsI am quite sure the second part of my answer still applies. You can set the category as a hint in the intent. In this case maybe in the intent of your notification context. Other than that you might also use flags for this. see this link for a notification creation with intent: stackoverflow.com/questions/13716723/…
-
nbtk over 6 yearsStill, If your oldest activity is MainActivity and now it is resumed, and then you receive push notification and you set the pendingIntent to open with CATEGORY_LAUNCHER, then you'll have 2 activities with this category. Probably on different tasks though
-
A. Binzxxxxxx over 6 yearsI am not exactly sure how it works with notifications. I never used them like you do it here. I am quite sure there is a easy way to do it with this approach but I did not touch android code since Q1 2014. Maybe you want to use a second category for this case? Or some flag? But I guess its ment to work like this. How about starting the main activity and adding some kind of meta info to open the correct activity then?
-
r3flss ExlUtr over 6 yearsGood info but you should put the update notice at the top so it's the first thing people see
-
Isac almost 6 yearsI think you should consider incorporating the sample code provided in the comments into the answer, to make it easier for future readers.
-
Mr.Drew over 5 yearsNow that
GET_TASKS
is depreciated, how can we get this same functionality? -
David Wasser over 5 years@Mr.Drew see the highest voted answer from @ raukodraug
-
dave o grady about 4 yearsexcellent answer. in my case after the user clicks on a notification the activity might be the root if they closed the application before
-
Kanchan Pal almost 3 yearsAs per the android docs, Single task activity is created in a new task and this activity is pushed as the root of the task. But I see in Single task activity this
isTaskRoot()
method is coming as false. Can anyone help me understand this?