Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show dialog yes/No before leaving the app via Back button

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?

like image 757
Saideira Avatar asked Oct 28 '10 17:10

Saideira


People also ask

How do I close apps on back button?

While some app developers use it to close their apps, some use it to traverse back to the app's previous activity. Many apps require the user to press the 'Back' button two times within an interval to successfully close the application, which is considered the best practice.

How do you override a back press on a flutter?

To override the back button in Flutter and show the confirmation dialog, you can use the same WillPopScope widget. Whenever you get the back button pressed callback, show the alert dialog asking for exit confirmation.


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

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().

like image 194
Vit Khudenko Avatar answered Oct 21 '22 08:10

Vit Khudenko