天天看點

Android按傳回鍵(後退鍵)Back鍵事件捕獲的兩種方法

package zhangphil.back;

import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

	// 列印事件的标簽
	private final String TAG = "Phil";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate()");
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.d(TAG, "onStart()");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.d(TAG, "onRestart()");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "onResume()");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "onPause()");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "onStop()");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy()");
	}

	// 捕獲傳回鍵的方法1
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 按下BACK,同時沒有重複
			Log.d(TAG, "onKeyDown()");
		}

		return super.onKeyDown(keyCode, event);
	}

	// 捕獲傳回鍵的方法2
	@Override
	public void onBackPressed() {
		Log.d(TAG, "onBackPressed()");
		super.onBackPressed();
	}
}
           

繼續閱讀