Could not catch android button event

I am trying to catch the back button event for Android. I know that there is already a lot about it, but my code does not work as the given examples. Here is my code snippet to capture the event:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
    if(keyCode == KeyEvent.KEYCODE_BACK){
        Log.d(TAG, "back key captured");
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

I also tried this:

@Override
public void onBackPressed(){
    Log.d(TAG, "in onBackPressed");
    finish();
}

LogCat exit that was fired or event is not displayed. Does anyone know the reason for this?

Thank.

+5
source share
6 answers

Another method is to override the method public void onBackPressed(). It is more simple and easy to do.

+15
source

To receive a keyboard event, the View must have focus. To make it use:

view.setFocusableInTouchMode(True);
view.requestFocus();
+8

? , , .

+2

private long lastBackPressTime = 0;
    @Override
public void onBackPressed() {
    if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
        Toast.makeText(this, R.string.backButtonWarning, 4000).show();
        this.lastBackPressTime = System.currentTimeMillis();
    } else {
        super.onBackPressed();
    }
}

- ADT, te apropiate (R). , ,

+1

, , , ! , onResume() Activity . , - - , , "onResume" , - , "" , , -.

+1

.

/**
   * onKeyDown method
   * 
   * Executes code depending on what keyCode is pressed.
   * 
   * @param int keyCode
   * @param KeyEvent
   *          event KeyEvent object
   * 
   * @return true if the code completes execution, false otherwise
   * 
   */
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {        
    switch (keyCode) {
    case KeyEvent.KEYCODE_BACK:
      Log.d(TAG, "back key captured");

      this.onBackPressed();

      //You could also use this.moveTaskToBack(true) to return to the Home screen

      return true;

    default:
      return super.onKeyDown(keyCode, event);
    }
  }// end onKeyDown
-1

All Articles