Which method is called when I press back key on my phone?
I have an app that has a lot of activities, all created with ONACTIVITYRESULT
.
Which method is called when I press back key?
I need to know it because I have to开发者_运维问答 override/implement
code on it.
The method that is called for is: onKeyDown
of your current Activity
.
You can use this to target all Android versions:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return super.onKeyDown(keyCode, event);
}
If you're targeting newer Android devices, the API for Android 2.0
and above has made things a little easier:
@Override
public void onBackPressed() {
return;
}
You could try this. I have this code on the page after checking for the licence. If my user presses back, I do not want them to go onto the licence check page again so I just quit the app. You don't have to quit the app, you can call whatever you want in here...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// Quit if back is pressed
if (keyCode == KeyEvent.KEYCODE_BACK)
{
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
精彩评论