Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Back button from closing my application

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?

like image 508
Keith Adler Avatar asked Jun 29 '11 00:06

Keith Adler


3 Answers

A more succinct solution:-

@Override
public void onBackPressed() {
    // do nothing. We want to force user to stay in this activity and not drop out.
}
like image 195
Nebu Avatar answered Oct 08 '22 23:10

Nebu


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.

like image 40
jondavidjohn Avatar answered Oct 08 '22 23:10

jondavidjohn


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.

like image 43
denis.solonenko Avatar answered Oct 08 '22 23:10

denis.solonenko