Search code examples
androidback-button

onPause not called when back button pressed?


It was my understanding, obviously wrong, that onPause() is called whenever the back button is pressed? Now in my code I've put this onPause() event:

@Override
protected void onPause(){
    super.onPause();        

    if(!_END_GAME){
        Builder _alert = new AlertDialog.Builder(this)
        .setMessage("onPause, with game NOT over!");
        _alert.setNeutralButton("OK.",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                arg0.dismiss(); // Kills the interface
                System.runFinalizersOnExit(true);
                finish();
            }
        });
        _alert.setTitle("Your Score!");
        _alert.show();
    }

}

Now the problem is, the dialog does not launch what-so-ever, and then the code errors out. I put the dialog there to try to visualize where the onPause() was called and help me debug some other variables and such. Yet like I said it never even gets shown. Any ideas why this would be? Is there a function that is launched prior to onPause() when the back button is pressed? Thank you in advance for any info.


Solution

  • You should check for the back button by overriding onKeyDown, not testing in onPause. onPause gets called whenever your activity is no longer in the background leaves the foreground; it is not necessarily finishing. (You can check isFinishing() for that.) See here for more info on handling the back key.