User friendly double back exit

 Программирование  android

This is the common Android UI pattern to use double Back press to confirm exit from application. It has simple implementation. However there is one thing developers do not think about: when user presses Back the toast with confirmation message is continuing to be displayed after application is already quit.

Here is the solution to this issue:

private Toast backToast;

public void onCreate(Bundle savedInstanceState) {
    // Create toast in advance
    backToast = Toast.makeText(this, "Press Back again to quit", Toast.LENGTH_SHORT);
    secondBack = false;

final Handler backHandler = new Handler();

public void onBackPressed() {
    if (secondBack) {
        // Cancel the toast to make it stop showing
    } else {
        // Be ready for the second Back
        secondBack = true;
        // Show toast;
        // Initiate timeout
        backHandler.postDelayed(new Runnable() {
            public void run() {
                secondBack = false;
        }, 2000); // Toast.LENGTH_SHORT lasts for 2000 ms