Devrath
Devrath

Reputation: 42824

Android - How to detect the final Activity in the stack

I use the code below to check the final Fragment in an Activity to pop a dialog

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Check if there is only one fragment
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                DlgUniversalError.shallIQuit(this, getApplicationContext()
                        .getResources().getString(R.string.doYouWantToQuit),
                        getSupportFragmentManager());
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

Now suppose i have a set of Activitys. How can I perform the same for an Activity whether the Activity is the last in the stack, and pop a quit dialog ?

Upvotes: 2

Views: 4761

Answers (1)

Yash Sampat
Yash Sampat

Reputation: 30601

Say you have Activities 1,2,3 ... and their flow is:

Activity 1 -> Activity 2 -> Activity 3 -> ... and so on

The only choice you really have is that in your Activity 1, override the onBackPressed() method as follows:

@Override
public void onBackPressed(){

    /* Call the Quit Dialog here. If user presses YES,
     * call super.onBackPressed(), else if user presses NO,
     * do nothing. */

}

The Fragment backstack is local to the application, whereas the Activity backstack is local to a task. Now there are a couple of ways to check the status of the current task's Activity backstack:

1. Say your Activity flow is

A1 -> A2 -> A3 -> A1 -> A2 -> A3 -> A1 ...

It is possible to ensure that Activity 1 always starts with an empty backstack. Each time you start Activity 1 with startActivity(), call it with the FLAG_ACTIVITY_CLEAR_TOP flag:

Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);

2. There is a method called isTaskRoot() that lets you know if an Activity is the first Activity in that task, i.e. the last Activity on that task's backstack. This looks promising.

3. Turns out there is one more way to determine if an Activity is the last one on the backstack:

    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())) {
        /* do whatever you want e.g. super.onBackPressed() etc. */
    }

For this, add android.permission.GET_TASKS permission to your manifest.

So there ... :)

Upvotes: 7

Related Questions