对于Home键的监听不是那么容易,因为Home键可以将程序退出放在后台,所以这个事件是直接分发给系统,系统接收到之后做相应处理,Home键的事件不是直接传递到应用里面.所以在上述监听Back键的代码中,相应的回调中是收不到Home键的事件的.
参考文后的博客链接,对Home键的监听主要通过注册广播接收器实现,拦截让窗口关闭的系统动作,然后根据Intent里面的具体参数,分析当前到底是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)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
Log.i(LOG_TAG, "reason: " + reason);
if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
Log.i(LOG_TAG, "homekey");
}
else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
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)) {
Log.i(LOG_TAG, "assist");
}
}
}
}