16

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

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
user1288005
  • 890
  • 2
  • 16
  • 36
  • http://stackoverflow.com/questions/5975811/how-to-check-if-an-activity-is-the-last-one-in-the-activity-stack-for-an-applica – Nouman Ghaffar Nov 19 '15 at 10:17
  • @NoumanGhaffar : Have a look on image name of my topActivity is not same as last activity. It shows launcher activity as topActivity. This only happens when I come from deeplinks. This problem is particular to deeplinks. So I alreadt tried the same but it didn't worked out for me. – user1288005 Nov 19 '15 at 10:27
  • You are getting the activity count from the first task in tasklist(may not be the task for your activity if started in a new task) – Harish Sharma Nov 19 '15 at 10:50
  • please refer this link http://stackoverflow.com/questions/33581311/android-m-how-can-i-get-the-current-foreground-activity-package-namefrom-a-ser/33828821#33828821 – Kishan Soni Nov 28 '15 at 08:56
  • you **could** (if everything else fails), maintain this stack yourself with a little bit of work. Add a stack in your `Application` class (supposing you do have your own `Application` class) and every time on the `onCreate` of your activities (all of them), put the activity to that stack in the application and on the `onDestroy()`, pop them. This way you can check the status of the live activities. – kha Nov 30 '15 at 08:59

5 Answers5

5

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();
}
anthorlop
  • 1,771
  • 1
  • 11
  • 11
  • isTaskRoot returns true for the _first_ activity in the stack: https://developer.android.com/reference/android/app/Activity#isTaskRoot%28%29 – Adam Johns Aug 07 '18 at 06:47
2

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");
}
life evader
  • 970
  • 8
  • 16
1

Quoting From ActivityManager.RunningTaskInfo

Information you can retrieve about a particular task that is currently "running" in the system. Note that a running task does not mean the given task actually has a process it is actively running in; it simply means that the user has gone to it and never closed it, but currently the system may have killed its process and is only holding on to its last state in order to restart it when the user returns.

                   String getLastOpenClass ;// Global 

                    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
                    List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
                    ComponentName componentInfo = taskInfo.get(0).topActivity;
                    componentInfo.getPackageName();
                    getLastOpenClass=taskInfo.get(0).topActivity.getClassName();
                    if(getLastOpenClass.equals("Your_Class_Name"))
                    {

                    }else{

                    }

Give permission <uses-permission android:name="android.permission.GET_TASKS" />

The ActivityManager keeps a record of the runnings task and the topmost task .

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

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

Please Check How can I get the current foreground activity package name

http://developer.android.com/intl/es/reference/android/app/ActivityManager.html#getRunningTasks%28int%29

Community
  • 1
  • 1
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0

Please note that the below solution will only work on API14+.

Create a custom application class;

public class App extends Application {

    private int created;

    @Override
    public void onCreate() {
        registerActivityLifecycleCallbacks(new Callbacks());
    }

    public int getCreated() {
        return created;
    }

    private class Callbacks implements ActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            created++;
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            created--;
        }
    }
}

Register it in your AndroidManifest.xml in the application element;

<application name=".App"/>

And in your activity opened through a deep link use the following piece of code;

@Override
public void onBackPressed() {
    if (((App) getApplicationContext()).getCreated() == 1) {
        // start your home activity
    }

    super.onBackPressed();
}

I wrote this off the top of my head so I haven't had a chance to test it, but theoretically it should work.

Martin
  • 1,775
  • 1
  • 13
  • 10
0

Specify parent activity for desired Activity, like :

<activity
    android:name=".DesiredActivity"
    android:parentActivityName="com.packagename.HomePage" >
    <!-- The meta-data element is needed for versions lower than 4.1 -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.packagename.HomePage" />
</activity>

With the parent activity declared, you can use the NavUtils APIs to synthesize a new back stack by identifying which activity is the appropriate parent for each activity.

override onBackPressed as :

@Override
public void onBackPressed() {
        Intent intent = NavUtils.getParentActivityIntent(this);
        startActivity(intent);
        super.onBackPressed();
}

Android developer's site has a very good resource for same problem. Please refer to link http://developer.android.com/training/implementing-navigation/temporal.html#SynthesizeBackStack

abhishesh
  • 3,246
  • 18
  • 20