Search code examples
javaandroidoverridingonkeydown

Overriding the back button


I have this code for overriding the back button and making it act like the home button:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

It is working perfectly. My question is if there is one location I can put this to make it work for all activities. Right now I have this method replicated in every activity.


Solution

  • Create your own BaseActivity and extend it with Activity, override back there. Now in your whole app instead using Activity use that BaseActivity.

    Something like this:

    public abstract class BaseActivity extends Activity 
    {
        final protected void onCreate(Bundle savedInstanceState)
       {
        super.onCreate(savedInstanceState);
        onCreate_Impl(savedInstanceState);
       }
    
       abstract protected void onCreate_Impl(Bundle savedInstanceState);
    }    
    

    You have to use onCreate_Impl in place of onCreate.