大部分androidapp都默认提供双击返回按钮退出程序的功能,这个功能实现起来非常简单,只需要重写activity的onKeyDown事件即可,完整的代码如下:
private long exitTime = 0;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN)
{
if (System.currentTimeMillis() - exitTime > 2000)
{
Toast.makeText(getApplicationContext(), "再按一次退出程序",
Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else
{
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}