连续点击退出app
public class MainActivity extends AppCompatActivity {
private long lastTime=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&&event.getAction()==KeyEvent.ACTION_DOWN){
if((System.currentTimeMillis()-lastTime)>2000){
Toast.makeText(MainActivity.this, "在按一次退出程序", Toast.LENGTH_SHORT).show();
lastTime=System.currentTimeMillis();
}else {
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}
单击弹出dialog退出app
- 单击back弹出dialog,强制禁止back取消dialog的消失
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog exitDialog = new AlertDialog.Builder(this).create();
exitDialog.setTitle("系统提示");
exitDialog.setMessage("你确定要退出吗");
exitDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
exitDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Main2Activity.this, "我已经取消了", Toast.LENGTH_SHORT).show();
}
});
exitDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return true;
}
return true;
}
});
exitDialog.show();
}
return super.onKeyDown(keyCode, event);
}
}
验证
以上两种方法全部经过试验,可以拿来使用