Search code examples
androidandroid-activityactivity-finish

How to press back button in android programmatically?


In my app I have a logout functionality. If user clicks logout it goes to home screen. Now I am exiting my app by pressing back button. But what I want is I need to exit automatically(i.e Programmatically) as same like as back button functionality. I know by calling finish() will do the functionality. But the thing is it goes to the previous activity.


Solution

  • onBackPressed() is supported since: API Level 5

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            onBackPressed();
        }
    }
    
    @Override
    public void onBackPressed() {
        //this is only needed if you have specific things
        //that you want to do when the user presses the back button.
        /* your specific things...*/
        super.onBackPressed();   
    }