现在在一些app中没用menu菜单来实现退出程序,很简化地使用点击两次返回键来实现退出程序,这个方法简单实用,软件退出不在赖在后台。
代码实现,重写onKeyDown来监听:
public class MainActivity extends AppCompatActivity {
private long waitTime = 2000;
private long touchTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//2秒之类连续点击2次返回键则退出程序
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
long currentTime = System.currentTimeMillis();
if ((currentTime - touchTime) > waitTime) {
Toast.makeText(this, "请再按一次退出", Toast.LENGTH_LONG).show();
touchTime = currentTime;
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
}