閱讀123 返回首頁    go 微軟 go windows


android 4.0以後對HOME鍵的捕捉

package com.ljj.listeninghome;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
 * 所有Activity繼承該類,該類監測到home鍵的點擊時的事件
 * 
 * @author lijingjin
 * 
 */
public class BaseActivity extends Activity {
	// 監聽HOME鍵
	HomeKeyEventBroadCastReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 監聽home鍵廣播
		receiver = new HomeKeyEventBroadCastReceiver();
		registerReceiver(receiver, new IntentFilter(
				Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
		static final String SYSTEM_REASON = "reason";
		static final String SYSTEM_HOME_KEY = "homekey";// home key
		static final String SYSTEM_RECENT_APPS = "recentapps";// long home key

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
				String reason = intent.getStringExtra(SYSTEM_REASON);
				if (reason != null) {
					if (reason.equals(SYSTEM_HOME_KEY)) {
						// home key處理點
						Log.e("homekey", "home鍵被點擊");
						Toast.makeText(BaseActivity.this, "Home鍵被點擊", Toast.LENGTH_SHORT).show();
					} else if (reason.equals(SYSTEM_RECENT_APPS)) {
						// long homekey處理點
						 Log.e("homekey", "長按home鍵");
						 Toast.makeText(BaseActivity.this, "Home鍵長按", Toast.LENGTH_SHORT).show();
					}
				}
			}
		}
	}
}



package com.ljj.listeninghome;

import android.os.Bundle;
/**
 * 該類繼承BaseActivity,在BaseActivity中監控HOME鍵
 * @author lijingjin
 *
 */
public class MainActivity extends BaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}



最後更新:2017-04-03 12:53:56

  上一篇:go Pelican + Github 搭建自己的靜態博客
  下一篇:go [Android設計模式]Android退出應用程序終極方法