Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android實現雙擊退出程序的效果

Android實現雙擊退出程序的效果

編輯:關於Android編程

下面我收集了幾種實現方法

1

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);
	}

 

2.

private static long back_pressed_time;
	private static long PERIOD = 2000;

	@Override
	public void onBackPressed()
	{
		if (back_pressed_time + PERIOD > System.currentTimeMillis()) 
			super.onBackPressed();
		else Toast.makeText(this, "再按一次退出!", Toast.LENGTH_LONG).show();
		back_pressed_time = System.currentTimeMillis();
	}

 

3.
	private long lastPressedTime;
	private static final int PERIOD = 2000;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			switch (event.getAction()) {
			case KeyEvent.ACTION_DOWN:
				if (event.getDownTime() - lastPressedTime < PERIOD) {
					Toast.makeText(getApplicationContext(), "Press again to exit.",
							Toast.LENGTH_SHORT).show();
					finish();
				} else {

					lastPressedTime = event.getEventTime();
				}
				return true;
			}
		}
		return false;
	}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved