Show yes / No before exiting the application using the back button

If the user clicks the "Back" button several times, I need a way to determine when they are in the most recent action of my task / application and show "Do you want to exit?". before they return to the main screen or all the previous application that they had.

It’s easy enough to hook onkeypressed(), but how can I understand that this is the “last” action in the task?

+5
source share
3 answers

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

AndroidManifest.xml:

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

, Activty :

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

youd , Activity.finish().

+6

Android-, Android:

BACK, , ( ). , .
+2

All Articles