android 再按一次后退键退出应用程序
方法一:
private static Boolean isExit = false; private static Boolean hasTask = false; Timer tExit = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { isExit = false; hasTask = true; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { System.out.println("TabHost_Index.java onKeyDown"); if (keyCode == KeyEvent.KEYCODE_BACK) { if(isExit == false ) { isExit = true; Toast.makeText(this, "再按一次后退键退出应用程序", Toast.LENGTH_SHORT).show(); if(!hasTask) { tExit.schedule(task, 2000); } } else { finish(); System.exit(0); } } return false; }
方法2:
public class BackActivity extends Activity { private static final String TAG = "BackActivity"; private long mLastBackTime = 0; private long TIME_DIFF = 2 * 1000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { long now = new Date().getTime(); if (now - mLastBackTime < TIME_DIFF) { Log.d(TAG, "back, finish"); return super.onKeyDown(keyCode, event); } else { Log.d(TAG, "after 2s, toast"); mLastBackTime = now; Toast.makeText(this, "再点一次将推出", 2000).show(); } return true; } return super.onKeyDown(keyCode, event); } }
建议用方法2