How to Prevent Accidental App Exit w/in Android Fragments/Activities?

我的未来我决定 提交于 2019-12-03 09:16:00

This functionality can easily be implemented by overriding main activity's onBackPressed() method. In this example when user presses back button then the app will display a toast for 4 seconds on which time a new back press terminates the app immediately.

ref

You can put it in a BaseActivity that extends Activity like this:

public class BaseActivity extends Activity{

    private Toast toast;
    private long lastBackPressTime = 0;
    . . .

    /**
     * Prevent accidental app exit by requiring users to press back twice when
     * the app is exiting w/in 4sec
     */
    @Override
    public void onBackPressed() {
      if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
        toast = Toast.makeText(this, "Press back again to close this app", 4000);
        toast.show();
        this.lastBackPressTime = System.currentTimeMillis();
      } else {
        if (toast != null) {
        toast.cancel();
      }
      super.onBackPressed();
     }
    }
    . . . 
}

EDIT: ADDED FRAGMENT BACKSTACK COMPATABILITY

For use to detect the last fragment in a bacstack whos application is solely using fragments, I strongly suggest putting your dispatchKeyEvents in a BaseActivity class and implementing the above method like so:

public class BaseActivity extends Activity {

    public boolean dispatchKeyEvent(KeyEvent event) {
        int backCount = getFragmentManager().getBackStackEntryCount();
        int action = event.getAction();
        int keyCode = event.getKeyCode();

        FragmentManager fm = getFragmentManager();

    . . .

        case KeyEvent.KEYCODE_BACK :
                if (action == KeyEvent.ACTION_DOWN && backCount == 0) {
                    onexitNotify();
                }else {
                    fm.popBackStack();
                }
                return true;

            default :
                return super.dispatchKeyEvent(event);
        }
    }

/**
 * Prevent accidental app exit by requiring users to press back twice when
 * the app is exiting w/in 8sec
 */
    private Toast toast;
    private long lastBackPressTime = 0;

    public void onexitNotify() {
        if (this.lastBackPressTime < System.currentTimeMillis() - 8000) {
            toast = Toast.makeText(this, "Press back again to close this app", 8000);
            toast.show();
            this.lastBackPressTime = System.currentTimeMillis();
        } else {
            if (toast != null) {
                toast.cancel();
            }
            super.onBackPressed();
        }
    }
}

*If you're using 2.0+, onBackPressed() simplifies the amount of code needed so onKeyDown() is not needed.

Per androd patterns recomendation:

Some applications prompt user when it is about to exit. This seems to be particularly common with game apps. This practice is not recommended in normal applications. A confirmation prompt would disrupt user's normal workflow. Even in games using this option should be very carefully considered.

You can check when the back key is pressed in the main activity of your app. You can then show user an alertdialog for a confirmation to exit.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if(keyCode == KeyEvent.KEYCODE_BACK) {          
        checkExit();             
        return true;
    }       
    else {
        return super.onKeyDown(keyCode, event);
    }

}

private void checkExit()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);        
    builder.setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {

                   //take actions here accordingly as the user has pressed yes
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });      
    AlertDialog alert = builder.create();
    alert.show();       
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!