Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch device back button event in android?

Tags:

android

I have open pdf file through my application.when click on device back button it is automatically come back to my application .It is working fine.Here i want catch back button event in device.I override the back button.but it is not working.please help me.

like image 646
SuReSh PaTi Avatar asked Jun 29 '12 16:06

SuReSh PaTi


People also ask

How can I check back button is pressed in Android?

In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.

How do you close a back pressed app on Android?

For that, you need to override the onBackPressed() method. Usually, this method opens up the top activity in the stack. On back button pressed you want to exit that activity and also you don't want to add this to the activity stack. Call finish() inside the onBackPressed() method.

What is hardware back button in Android?

The hardware back button is found on most Android devices. In native applications it can be used to close modals, navigate to the previous view, exit an app, and more. By default in Ionic, when the back button is pressed, the current view will be popped off the navigation stack, and the previous view will be displayed.

How do I get my old Android activity back?

Android activities are stored in the activity stack. Going back to a previous activity could mean two things. You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.


2 Answers

This is an example of what you are asking:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        //do your stuff
    }
    return super.onKeyDown(keyCode, event);
}
like image 200
Stefano Ortisi Avatar answered Oct 19 '22 03:10

Stefano Ortisi


just call the foolowing function this will close current activity and move you to the previous screen

finish();
like image 2
coading fever Avatar answered Oct 19 '22 03:10

coading fever