Android 再按一次退出程序的实现方法
程序员文章站
2023-11-14 08:21:40
第一种(handler+标志位)复制代码 代码如下:private boolean isexit; private handler ha...
第一种(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);
}