Skip to content Skip to sidebar Skip to footer

How To Make Some Code Execute When The User Leaves The Current Activity (pressing Back Hardware Button)

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

Solution 1:

Override onBackPressed():

@OverridepublicvoidonBackPressed() {
    //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()

Solution 2:

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

// Sets functionality of the hard buttons on the device@OverridepublicbooleanonKeyUp(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Code
    }
    returntrue;
}

Post a Comment for "How To Make Some Code Execute When The User Leaves The Current Activity (pressing Back Hardware Button)"