关于android app两次点击返回键退出的处理

时间:2022-09-20 18:38:32

现在的android app在开发时,引入了两次点击返回键退出app的设计

为了避免用户误触,这个设计很人性化

中文网上社区有些同学贴了一些实现的例子,我觉得不是很好

代码如下

 public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((System.currentTimeMillis() - mExitTime) > 2000) {
Object mHelperUtils;
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
mExitTime = System.currentTimeMillis(); } else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}

其中显示的调用了finish方法,更有甚者,显示的调用system.exit方法,以讹传讹,造成程序bug,降低程序的用户体验

在android开发网的文档上可以看到:

You can shut down an activity by calling its finish() method. 
You can also shut down a separate activity that you previously started by calling finishActivity(). Note: In most cases, you should not explicitly finish an activity using these methods.
As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you,
so you do not need to finish your own activities.
Calling these methods could adversely affect the expected user experience and
should only be used when you absolutely do not want the user to return to this instance of the activity.

无论如何,主动去调用finish是懒人的烂代码,我翻遍文档找不到一篇文章会建议码农主动去调用finish的。

在*上,有个非常好的示例,代码如下,建议代码入坑的码农学习这个方案

 private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
private long mBackPressed; @Override
public void onBackPressed()
{
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
{
super.onBackPressed();
return;
}
else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); } mBackPressed = System.currentTimeMillis();
}
 private boolean doubleBackToExitPressedOnce;
private Handler mHandler = new Handler(); private final Runnable mRunnable = new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}; @Override
protected void onDestroy()
{
super.onDestroy(); if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
} @Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
} this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); mHandler.postDelayed(mRunnable, 2000);
}