本文提供了两种触摸返回键提示退出的两种方法
1.触摸返回键弹出对话框
public void onBackPressed(){ //android 2.0以上的 <a target=_blank href="http://blog.csdn.net/u010717419/article/details/24481537">点击解释为什么</a> Toast.makeText(this, "你点击了返回键", Toast.LENGTH_LONG).show(); AlertDialog.Builder builder = new Builder(this); builder.setTitle("提示"); builder.setMessage("确认要退出吗"); builder.setPositiveButton("确认", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //不做任何动作 } }); builder.create().show(); }2.触摸两次返回键退出
private long currentBackPressedTime = 0; private static final int BACK_PRESSED_INTERVAL = 2000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onBackPressed(){ //1.当前的获取的毫秒数-预定值(0)肯定大于2s //4.当下次再按时当前值跟赋予后的设定值比较 if(System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL){ //2.把当前的毫秒数赋予预定值 currentBackPressedTime = System.currentTimeMillis() ; //3.弹出框 Toast.makeText(this, "再按一次退出", 0).show(); }else{ //若当前值-设定值<2s 则执行: finish(); } }