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. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
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

Toast.makeText(AndroidBackButtonActivity.this,
"BACK key pressed",
Toast.LENGTH_LONG).show();

return true; //processed
}else{
//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