private static Boolean isExit = false;
private static Boolean hasTask = false;
Timer tExit = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
isExit = false;
hasTask = true;
}
};
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK){
// System.out.println("user back down");
if(isExit == false ) {
isExit = true;
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
if(!hasTask) {
tExit.schedule(task, 2000);
}} else {
}
finish();
System.exit(0);
}
}
return false;
}
在做安卓应用是我们经常要判断用户对返回键的操作,一般为了防止误操作都是在用户连续按下两次返回键的时候提示用户是否退出应用程序。
第一种实现的基本原理就是,当按下BACK键时,会被onKeyDown捕获,判断是BACK键,则执行exit方法。
在exit方法中,会首先判断isExit的值,如果为false的话,则置为true,同时会弹出提示,并在2000毫秒(2秒)后发出一个消息,在Handler中将此值还原成false。如果在发送消息间隔的2秒内,再次按了BACK键,则再次执行exit方法,此时isExit的值已为true,则会执行退出的方法。
package com.gaolei.exitdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.widget.Toast; public class MainActivity extends Activity { // 定义一个变量,来标识是否退出 private static boolean isExit = false; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); isExit = false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); return false; } return super.onKeyDown(keyCode, event); } private void exit() { if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); // 利用handler延迟发送更改状态信息 mHandler.sendEmptyMessageDelayed(0, 2000); } else { finish(); System.exit(0); } } }第二种实现方式,通过记录按键时间计算时间差实现:
package com.gaolei.exitdemo; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.widget.Toast; public class MainActivity extends Activity { private long exitTime = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); return false; } return super.onKeyDown(keyCode, event); } public void exit() { if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); System.exit(0); } } }