再按一次退出程序 Android 再按一次退出程序的实现方法
人气:0想了解Android 再按一次退出程序的实现方法的相关内容吗,在本文为您仔细讲解再按一次退出程序的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:再按一次,退出程序,下面大家一起来学习吧。
第一种(Handler+标志位)
复制代码 代码如下:
private boolean isExit;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
isExit = false;
}
};
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
if(!isExit){
isExit = true;
handler.sendEmptyMessageDelayed(0, 1500);
Toast.makeText(this, "再按一次推出程序", 1000).show();
return false;
}else{
finish();
}
}
return super.onKeyDown(keyCode, event);
}
第二种(记录点击的时间)
复制代码 代码如下:
private long exitTimeMillis = System.currentTimeMillis();
@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){
long currentTime = System.currentTimeMillis();
if(currentTime-exitTimeMillis==0||currentTime-exitTimeMillis>1500){
exitTimeMillis = System.currentTimeMillis();
Toast.makeText(this, "再按一次推出程序", 1000).show();
return false;
}else{
finish();
}
}
return super.onKeyDown(keyCode, event);
}
加载全部内容