android实现再按一次退出程序

方式一:

/**
*重写onKeyDown,实现再按一次退出程序,如果两次点击时间超过三秒则提示"再按一次退出程序"
*/
privatelongtouchTime=0;
@Override
publicbooleanonKeyDown(intkeyCode,KeyEventevent){
if(keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){
if((System.currentTimeMillis()-touchTime)>3000){
Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_SHORT).show();
touchTime=System.currentTimeMillis();
}else{
finish();
System.exit(0);
}
returntrue;
}
returnsuper.onKeyDown(keyCode,event);
方式二:

/**
*重写onKeyDown,实现按第二次返回键必退出程序
*/
privatebooleanisexit=false;
@Override
publicbooleanonKeyDown(intkeyCode,KeyEventevent){
if(keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0){
if(isexit){
finish();
}else{
isexit=true;
Toast.makeText(DairyMenuActivity.this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
}
returnfalse;
}
returnfalse;
}

方式三:

/**
*重写onKeyDown,实现根据提示退出程序
*/
@Override
publicbooleanonKeyDown(intkeyCode,KeyEventevent){
if(keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0){
exitdialog();
returnfalse;
}
returnfalse;
/**
*根据提示退出程序dialog
*/
protectedvoidexitdialog(){
AlertDialog.Builderbuilder=newBuilder(DairyMenuActivity.this);
builder.setMessage("确定要退出吗?");
builder.setTitle("温馨提示:");
builder.setPositiveButton("确认",
newandroid.content.DialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.cancel();
DairyMenuActivity.this.finish();
}
});
builder.setNegativeButton("取消",
newandroid.content.DialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,intwhich){
dialog.cancel();
}
});
builder.create().show();
}

你可能感兴趣的:(android)