1.点击back 键后,弹出对话框
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
final AlertDialog exit=new AlertDialog.Builder(this).create();
exit.setTitle("系统提示");
OnClickListener listener=new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch(which){
case AlertDialog.BUTTON1:
finish();
break;
case AlertDialog.BUTTON2:
exit.cancel();
break;
default:
break;
}
}
};
exit.setButton("确定", listener);
exit.setButton2("取消", listener);
exit.show();
}
return super.onKeyDown(keyCode, event);
}
2.如果是想要点击返回键,点击两次才返回时,为了防止意外点击情况
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode==event.KEYCODE_BACK){
if(System.currentTimeMillis()-time>2000){
time=System.currentTimeMillis();
}else{
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
3. 当用户点击自定义的退出按钮或返回键时,在onDestroy()里强制退出应用,或直接杀死进程
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode==event.KEYCODE_BACK){
new AlertDialog.Builder(this).
setIcon(R.drawable.aa4)
.setTitle(R.string.add_user)
.setMessage(R.string.action_settings)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(R.string.address, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
}
).show();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
}
4. 如果想要屏蔽back键,点击back键无效果
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
返回为true, 就无效果了。