[java]
Home鍵監聽:
1. 在onResum裡面注冊廣播,OnPause裡面注銷廣播。
2. 再廣播中攔截Intent.ACTION_CLOSE_SYSTEM_DIALOGS 這個Action ,通過獲取Reason字段 來判斷長按 還是單擊Home鍵。
下面看看代碼:
[java]
package com.way.common.util;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
/**
* Home鍵監聽封裝
*
* @author way
*
*/
public class HomeWatcher {
static final String TAG = "HomeWatcher";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
// 回調接口
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}
public HomeWatcher(Context context) {
mContext = context;
mRecevier = new InnerRecevier();
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
/**
* 設置監聽
*
* @param listener
*/
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
}
/**
* 開始監聽,注冊廣播
*/
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
/**
* 停止監聽,注銷廣播
*/
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
/**
* 廣播接收者
*/
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@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_DIALOG_REASON_KEY);
if (reason != null) {
L.i(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
// 短按home鍵
mListener.onHomePressed();
} else if (reason
.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
// 長按home鍵
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
然後再Activity中重寫OnResum方法
[java]
@Override
protected void onResume() {
// TODO Auto-generated method stub
mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(this);
mHomeWatcher.startWatch();
super.onResume();
}
再Onpause方法裡面注銷監聽
[java]
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mHomeWatcher.setOnHomePressedListener(null);
mHomeWatcher.stopWatch();
}
在Activity中實現OnHomePressedListener接口,我們就可以在實現方法裡面做我們自己的操作了