Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onKeyDown() or onBackPressed()

I want to implement the back button functionality in my application. In application whenever I'm clicking on back button in middle my control is going to login page directly, so can someone tell me where to override onKeyDown() or onBackPressed() methods?

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Log.e("back key pressed","Back key pressed");
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

because I'm writing this inside onCreate and outside onCreate also, but it's not working ......

like image 885
user1249134 Avatar asked Mar 05 '12 12:03

user1249134


2 Answers

Depends on whether or not you want to support pre-Android 2.0 phones. The onBackPressed() method was added to Android 2.0 (API 5).

You may want to read this post on the Android Developer blog for details:

http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

like image 148
zostay Avatar answered Nov 12 '22 23:11

zostay


see below code. write outside the onCreate

  @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event)  
  {  
         //replaces the default 'Back' button action  
         if(keyCode==KeyEvent.KEYCODE_BACK)  
         {  

                Intent intent = new Intent(currentActivity.this, RequiredActivity.class);
                finish();
                startActivity(intent); 

         }  
         return true;  
   }  
like image 5
Dharmendra Barad Avatar answered Nov 13 '22 00:11

Dharmendra Barad