Oct 15, 2011

Handle the BACK key by overriding onKeyDown()

onKeyDown(int keyCode, KeyEvent event) will be called when a key was pressed down and not handled by any of the views inside of the activity.

package com.BackButton;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class AndroidBackButtonActivity extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {

public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
//return super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_BACK){
//Process onKeyDown event of BACK key

"BACK key pressed",

return true; //processed
//Pass to original method to handle the key event
return super.onKeyDown(keyCode, event);


Related Post:
- For API level 5 (Android 2.1) or higher, onBackPressed() callback method is a alternative to handle BACK key.

No comments:

Post a Comment

Infolinks In Text Ads