在activity中添加如下代码
转载:https://www.cnblogs.com/hzauxx/p/11008772.html
//定义一个变量,来标识是否退出 private static int isExit=0;
Handler handler=new Handler(){ @Override public void handleMessage(Message msg){ super.handleMessage(msg); isExit--; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event){ if(keyCode== KeyEvent.KEYCODE_BACK){ isExit++; exit(); return false; } return super.onKeyDown(keyCode,event); } private void exit(){ if(isExit<2){ Toast.makeText(getApplicationContext(),"再按一次退出",Toast.LENGTH_SHORT).show(); //利用handler延迟发送更改状态信息 handler.sendEmptyMessageDelayed(0,2000); }else{ super.onBackPressed(); } }