昨天需要处理一个问题,需要监听home键。最开始想到使用onKeydonwn这个方法。但是发现home不能这样处理,onKeydonwn可以处理菜单键和back键,但home不能。因为home键是系统键,情况特殊一些。看了一下网上的资料,最后发现以下方法可以。
使用广播的方式来进行监听:
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");
}
}
}
}
广播接收器的注册有两种方式,一种是静态注册,即写在manifest里面声明;另一种是动态注册,即在Java代码里面注册.
静态注册:
<application ....>
....
<receiver android:name="com.mengdd.hellohome.HomeWatcherReceiver" >
<intent-filter>
<action android:name="android.intent.action.CLOSE_SYSTEM_DIALOGS" />
</intent-filter>
</receiver>
....
</application>
动态注册:
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();
}