前者:MainActivity:
package com.example.zong_zhishi; import android.os.Bundle; import android.app.Activity; import android.view.KeyEvent; import android.view.Menu; import android.widget.Toast; //按两次返回键退出程序 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } Exit exit = new Exit(); @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { pressAgainExit(); return true; } return super.onKeyDown(keyCode, event); } private void pressAgainExit() { if (exit.isExit()) { finish(); } else { Toast.makeText(getApplicationContext(), "再按一次退出程序", 1000).show(); exit.doExitInOneSecond(); } } }
辅助类:
Edit.class:
package com.example.zong_zhishi; import android.os.Handler; import android.os.HandlerThread; public class Exit { private boolean isExit = false; private Runnable task = new Runnable() { @Override public void run() { isExit = false; } }; public void doExitInOneSecond() { isExit = true; HandlerThread thread = new HandlerThread("doTask"); thread.start(); new Handler(thread.getLooper()).postDelayed(task, 1000); } public boolean isExit() { return isExit; } public void setExit(boolean isExit) { this.isExit = isExit; } }
第二种方法:
public boolean dispatchKeyEvent(KeyEvent event) { int keyCode=event.getKeyCode(); switch(keyCode) { case KeyEvent.KEYCODE_BACK: { if(event.isLongPress()) { this.stopService(intent); System.exit(0); return true; }else { return false; } } } return super.dispatchKeyEvent(event); }
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); }