Prevent Back button from closing my application

2019-04-26 14:48发布

问题:

I am using the following code in my application's activity to prevent it from closing my app on back.

/* Prevent app from being killed on back */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // Back?
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Back
            moveTaskToBack(true);
        }

        // Return
        return super.onKeyDown(keyCode, event);

    }

It does not work. The app is set to be Android 1.6 (API Level 4) compatible. Clicking on my application icon restarts my app at a Splash activity (which is the Main). How can I prevent my app from closing on back?

回答1:

Have you tried putting the super call in an else block so it is only called if the key is not KEYCODE_BACK ?

/* Prevent app from being killed on back */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        // Back?
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Back
            moveTaskToBack(true);
            return true;
        }
        else {
            // Return
            return super.onKeyDown(keyCode, event);
        }
    }

In all honesty though, you can't rely on this because once your app is placed in the background, at any moment it could be recycled for the system to reclaim memory.



回答2:

A more succinct solution:-

@Override
public void onBackPressed() {
    // do nothing. We want to force user to stay in this activity and not drop out.
}


回答3:

Even if you could do that, you should not. Enforcing users to keep your app in the memory all the time is not a good idea and will only annoy them.



回答4:

If need to navigate back as well as preventing from closing, then in Android WebView use this:

@Override
public void onBackPressed() {
    if (mWebView.canGoBack()) {
        mWebView.goBack();
        return;
    }

    // Otherwise defer to system default behavior.
    super.onBackPressed();
}