How to make some code execute when the user leaves

2019-03-01 03:19发布

As title says, how can I do it? I looked over the internet and it seems that you just can't do it.. Anyone knows how can it be done?

I mean, I know how to execute my code when the user presses a button that closes the activity, but what about the hardware back button?

Thank you!

2条回答
仙女界的扛把子
2楼-- · 2019-03-01 04:08

Override onBackPressed():

@Override
public void onBackPressed() {
    //code
}

This will execute when the back button is used. If you want to run code even when the user navigates to another activity, or uses the home button, override onPause()

查看更多
该账号已被封号
3楼-- · 2019-03-01 04:15

Here is the code if you choose to do the onKeyDown/onKeyUp approach as ρяσѕρєя suggested.

// Sets functionality of the hard buttons on the device
@Override 
public boolean onKeyUp(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Code
    }
    return true;
}
查看更多
登录 后发表回答