Android 实现点击两次BACK键退出应用
Jon54M
8年前
<p>思路:Android中捕获用户按键是在onKeyDown方法中,只需要判断用户按键是否是KEYCODE_BACK即后退键即可,剩下的即为判断两次点击BACK键时间间隔问题了</p> <p>第一种实现方式</p> <pre> <code class="language-java">package com.example.clickexittest; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; public class MainActivity extends Activity { private static final String TAG = MainActivity_Exit.class.getSimpleName(); // 定义一个变量,来标识是否退出 private static boolean isExit = false; private static Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); isExit = false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); return true; } return super.onKeyDown(keyCode, event); } private void exit() { if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", Toast.LENGTH_SHORT).show(); // 利用handler延迟发送更改状态信息 mHandler.sendEmptyMessageDelayed(0, 2000); } else { Log.e(TAG, "exit application"); this.finish(); } } }</code></pre> <p>在exit方法中,会首先判断isExit的值,如果为false的话,则置为true,同时会弹出提示,并在2000毫秒(2秒)后发出一个消息,在 Handler中将此值还原成false。如果在发送消息间隔的2秒内,再次按了BACK键,则再次执行exit方法,此时isExit的值已为 true,则会执行退出的方法。</p> <p>第二种实现方式</p> <pre> <code class="language-java">package com.example.clickexittest; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); private long clickTime = 0; //记录第一次点击的时间 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); return true; } return super.onKeyDown(keyCode, event); } private void exit() { if ((System.currentTimeMillis() - clickTime) > 2000) { Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", Toast.LENGTH_SHORT).show(); clickTime = System.currentTimeMillis(); } else { Log.e(TAG, "exit application"); this.finish(); // System.exit(0); } } }</code></pre> <p>判断用户两次按键的时间差是否在一个预期值之内,是的话直接直接退出,不是的话提示用户再按一次后退键退出。</p> <p> </p> <p>来自:http://www.androidchina.net/5652.html</p> <p> </p>