Android的back按键的两常用功能实现
1、实现再按一次退出
private long exitTime = 0; /* (1)Activity 继承TabActivity用onKeyDown无响应,使用dispatchKeyEvent (2) 一般的 Activity 用 onKeyDown 就可以了 (3) event.getRepeatCount() == 0增强程序健壮性,防止过快的点击back */ @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if(event.getAction()==KeyEvent.ACTION_DOWN&&event.getRepeatCount() == 0) { this.exitApp(); } return true; } return super.dispatchKeyEvent(event); } /********************************************************************* 退出程序 *********************************************************************/ private void exitApp() { // 判断2次点击事件时间 if ((System.currentTimeMillis() - exitTime) > 2000) {//currentTimeMillis()毫秒形式返回 Toast.makeText(MainActivity.this,"再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); } }
2、实现按一下弹出
单击确定后退出
我过程中使用的是多线程处理的方法。
(1)定义自己要弹出的窗口,并在初始化程序中调用
public void createDialog() { aDailog= new AlertDialog.Builder(Cal.this) .setIcon(R.drawable.ic_launcher) .setTitle(Cal.this.getString(R.string.tileQuit)) .setMessage("退出") .setNegativeButton(Cal.this.getString(R.string.cancel), new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ //uiProcess.soundPlay(); aDailog.dismiss(); }}) .setPositiveButton(Cal.this.getString(R.string.ensure),new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialoginterface, int i){ try { Thread.sleep(800); } catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); }}).create(); aDailog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getRepeatCount()==0)) { if(keyCode==KeyEvent.KEYCODE_BACK){ try { Thread.sleep(800); } catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); } return true; } return false; } }); }
(2)写back按键的事件(同第一种方法)并发送线程msg
@Override
public boolean dispatchKeyEvent(KeyEvent event){
switch(event.getKeyCode()){
case KeyEvent.KEYCODE_BACK:
if((event.getAction() == KeyEvent.ACTION_DOWN)&&(event.getRepeatCount()==0)){
//add the action to deal
//Toast.makeText(Cal.this, "再按一次退出", Toast.LENGTH_LONG).show();
msg.what = Cal.APPQUIT;
Log.v(TAG, msg.toString());
handler.sendEmptyMessageDelayed(msg.what, 20);
//aDailog.show();
}
return true;
}
return super.dispatchKeyEvent(event);
}
(3)线程程序处理
private static Handler handler=new Handler(){
@Override
public void handleMessage(Message msg){
switch(msg.what){
case Cal.APPQUIT:
aDailog.show(); break;
}
}
};
整体程序还是非常简单的,以上是经过我的测试。当然在定义变量时:
public static final byte APPQUIT=1;
private static Message msg = new Message();
private static AlertDialog aDailog;
不能少。
******************************************************
2013-4-22 飞扬小米(记)