Disable the back button when closing the application

I use the following code in my application activity to prevent it from closing my application.

/* 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);

    }

This does not work. The application is configured for compatibility with Android 1.6 (API Level 4). Clicking on the icon of my application restarts my application in the active Splash mode (which is the main one). How can I prevent my application from closing?

+5
source share
4 answers

Have you tried to put the call superin the else block, so it is called only 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);
        }
    }

, , , , , .

+8

: -

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

Even if you can do it, you should not. Forcing users to keep your application in memory all the time is not a good idea and will only annoy them.

+1
source

If you need to go back and also prevent 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();
}
0
source

All Articles