对back键设置监听器,重写Activity.onKeyDown()方法即可实现功能;程序如下:
long keydowmtime=0;//按键按下时的时间 long eventtime=0;//事件发生的时间 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub eventtime=event.getEventTime(); if(keydowmtime==0){ keydowmtime=event.getDownTime(); }else { if((eventtime-keydowmtime)<1000){//即两次点击时间小于1s时退出程序,否则,复位 MainActivity.this.finish(); }else{ keydowmtime=0; } } if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { Toast.makeText(MainActivity.this,"再按一次退出", Toast.LENGTH_SHORT).show(); } return super.onKeyDown(keyCode, event); } }
原文:http://www.cnblogs.com/mf0819/p/3840843.html