I want to know if user would return to the home screen if he exit the current activity.
-
1this might help: http://stackoverflow.com/questions/2590581/activities-stack – bigstones May 12 '11 at 09:42
11 Answers
I'm going to improve on the comment of @H9kDroid as the best answer here for people that have a similar question. (Original link)
You can use isTaskRoot() to know whether the activity is the root of a task.

- 4,555
- 31
- 31
- 45

- 11,519
- 4
- 35
- 37
-
1can you please provide the single line of code so that its clear on how to use isTaskRoot. Thanks. – Kaveesh Kanwal Mar 11 '15 at 15:55
-
21
-
3The only problem is that on <=4.4 I'm seeing it do different behavior than in >= 5.x. It seems to always return false. – chubbsondubs Sep 01 '16 at 15:49
-
I think you should consider incorporating the sample code provided in the comments into the answer, to make it easier for future readers. – Isac May 23 '18 at 09:45
-
excellent answer. in my case after the user clicks on a notification the activity might be the root if they closed the application before – dave o grady Apr 02 '20 at 21:11
-
1As 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? – Kanchan Pal Jul 24 '21 at 12:09
-
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

- 12,503
- 8
- 58
- 65
-
29H9kDroid has made a correct suggestion. The selected answer is a hack. One should do it the right way using the `isTaskRoot()` method. – Sufian Apr 02 '14 at 06:17
-
@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'. – sandrstar Jan 29 '15 at 06:34
-
2
-
Can i do the same thing for fragments. If yes then how ? Please help – Sagar Devanga Sep 04 '15 at 09:46
-
@SagarDevanga hm, probably you can try to use http://developer.android.com/reference/android/app/FragmentManager.html#getBackStackEntryCount%28%29 , 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. – sandrstar Sep 04 '15 at 13:43
-
Good info but you should put the update notice at the top so it's the first thing people see – r3flss ExlUtr Jan 23 '18 at 11:18
-
Now that `GET_TASKS` is depreciated, how can we get this same functionality? – Mr.Drew Oct 08 '18 at 07:51
-
1
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();
}
}

- 3,092
- 26
- 30
there is an easiest solution to this, you can use isTaskRoot() in your activity

- 309
- 2
- 7
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")

- 1,814
- 15
- 17
-
1Doesn't work if the activity gets killed and the activity stack is reconstructed - each activity by demand. – AlikElzin-kilaka Mar 03 '13 at 18:36
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.

- 1,198
- 8
- 13
-
1How 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. – Michael Feb 15 '16 at 04:28
-
2If a background service launches an Activity, perhaps you'd like to know whether or not that's the only Activity on the stack. – Matt W May 06 '17 at 00:48
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);

- 2,812
- 1
- 21
- 33
-
What if the activity is opened from push notification? They don't have the CATEGORY LAUNCHER – nbtk Sep 05 '17 at 08:56
-
I 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: https://stackoverflow.com/questions/13716723/open-application-after-clicking-on-notification – A. Binzxxxxxx Sep 05 '17 at 11:39
-
Still, 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 – nbtk Sep 06 '17 at 14:24
-
I 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? – A. Binzxxxxxx Sep 07 '17 at 12:02
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.

- 767
- 9
- 17
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
.

- 12,242
- 2
- 23
- 26
-
9That will not work since getCallingActivity() will return null if the activity was not started via startActivityForResult(). – H9kDroid Jun 03 '11 at 12:19
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.

- 775
- 6
- 14
if (activity.isTaskRoot){
toolbar.setNavigationOnClickListener{
activity.startActivity(Intent(activity,HomeActivity::class.java))
}
}
**kotlin version of this code **

- 51
- 6