views:

92

answers:

3

If user repeatedly presses back button, I need a way to detect when they are on the very last activity of my task/app and show "Do you want to exit?" dialog befor they return to Home Screen or whatever previous app they had running.

Its easy enough to hook onkeypressed(), but how do I figure out that this is a "last" activity in the task?

+1  A: 

Please review the Android Application Fundamentals, this violates the promoted behavior of an Android Application:

When the user presses the BACK key, the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed.
Brian Mansell
I wish we lived in a perfect world, but alas. The client wants the dialog. So, is there any way to peek at the global activity/task stack?
Saideira
Yes, I agree that clients want things they used to. With some kinds of clients we just can't say 'No' and just have to do what they want. Check my answer for how to do what you need.
Arhimed
+1  A: 

Afaik, there is not.

There are a few flags you can use to influence the history stack, but all within your application. Try this flags with your Intent:

FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY

FLAG_ACTIVITY_NO_HISTORY

FLAG_ACTIVITY_REORDER_TO_FRONT

FLAG_ACTIVITY_SINGLE_TOP

Peter Knego
+3  A: 

I think you can use smth like this in your Activity to check if it is the last one:

private boolean isLastActivity() {
    final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningTaskInfo> tasksInfo = am.getRunningTasks(1024);

    final String ourAppPackageName = getPackageName();
    RunningTaskInfo taskInfo;
    final int size = tasksInfo.size();
    for (int i = 0; i < size; i++) {
        taskInfo = tasksInfo.get(i);
        if (ourAppPackageName.equals(taskInfo.baseActivity.getPackageName())) {
            return taskInfo.numActivities == 1;
        }
    }

    return false;
}

This will also require to add a permission to your AndroidManifest.xml:

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

Thus in your Activty you can just use the following:

public void onBackPressed() {
    if (isLastActivity()) {
         showDialog(DIALOG_EXIT_CONFIRMATION_ID);
    } else {
         super.onBackPressed(); // this will actually finish the Activity
    }
}

Then in youd Dialog handle the button click to call Activity.finish().

Arhimed
brilliant! thank you.
Saideira