昨天需要處理一個問題,需要監(jiān)聽home鍵。最開始想到使用onKeydonwn這個方法描孟。但是發(fā)現(xiàn)home不能這樣處理驶睦,onKeydonwn可以處理菜單鍵和back鍵,但home不能匿醒。因為home鍵是系統(tǒng)鍵啥繁,情況特殊一些∏嗯祝看了一下網(wǎng)上的資料旗闽,最后發(fā)現(xiàn)以下方法可以。
使用廣播的方式來進行監(jiān)聽:
package com.mengdd.hellohome;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class HomeWatcherReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "HomeReceiver";
private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
private static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
private static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(LOG_TAG, "onReceive: action: " + action);
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
// android.intent.action.CLOSE_SYSTEM_DIALOGS
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
Log.i(LOG_TAG, "reason: " + reason);
if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
// 短按Home鍵
Log.i(LOG_TAG, "homekey");
}
else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
// 長按Home鍵 或者 activity切換鍵
Log.i(LOG_TAG, "long press home key or activity switch");
}
else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {
// 鎖屏
Log.i(LOG_TAG, "lock");
}
else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {
// samsung 長按Home鍵
Log.i(LOG_TAG, "assist");
}
}
}
}
廣播接收器的注冊有兩種方式,一種是靜態(tài)注冊,即寫在manifest里面聲明;另一種是動態(tài)注冊,即在Java代碼里面注冊.
靜態(tài)注冊:
<application ....>
....
<receiver android:name="com.mengdd.hellohome.HomeWatcherReceiver" >
<intent-filter>
<action android:name="android.intent.action.CLOSE_SYSTEM_DIALOGS" />
</intent-filter>
</receiver>
....
</application>
動態(tài)注冊:
private static HomeWatcherReceiver mHomeKeyReceiver = null;
private static void registerHomeKeyReceiver(Context context) {
Log.i(LOG_TAG, "registerHomeKeyReceiver");
mHomeKeyReceiver = new HomeWatcherReceiver();
final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(mHomeKeyReceiver, homeFilter);
}
private static void unregisterHomeKeyReceiver(Context context) {
Log.i(LOG_TAG, "unregisterHomeKeyReceiver");
if (null != mHomeKeyReceiver) {
context.unregisterReceiver(mHomeKeyReceiver);
}
}
然后在activity的OnResume和OnDePause中注冊和解除綁定
@Override
protected void onResume() {
super.onResume();
registerHomeKeyReceiver(this);
}
@Override
protected void onPause() {
unregisterHomeKeyReceiver(this);
super.onPause();
}