package com.ldw.parentcarefree.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
/**
* 监听系统按键,Home键、最近任务键
* Created by ldw on 2016/8/22.
*/
public class SystemKeyWatcher {
private static final String TAG = "SystemKeyWatcher";
private Context mContext = null;
private SystemKeyReceiver mSystemKeyReceiver = null;
private OnSystemKeyListener mOnSystemKeyListener = null;
/**
* 构造函数,必须传上下文参数
* @param context
*/
public SystemKeyWatcher(Context context) {
if(context == null){
throw new IllegalArgumentException("Parameters cannot be null");
}
mContext = context;
}
public interface OnSystemKeyListener {
/**
* Home键
*/
void onHomeKey();
/**
* 最近任务键
*/
void onRecentApps();
}
public void setOnSystemKeyListener(OnSystemKeyListener listener){
mOnSystemKeyListener = listener;
}
/**
* 注册
*/
public void register() {
//Log.v(TAG, "---register---");
if(mSystemKeyReceiver == null){
mSystemKeyReceiver = new SystemKeyReceiver();
}
IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
mContext.registerReceiver(mSystemKeyReceiver, homeFilter);
}
/**
* 注销
*/
public void unregister() {
//Log.v(TAG, "---unregister---");
if (mSystemKeyReceiver != null) {
mContext.unregisterReceiver(mSystemKeyReceiver);
mSystemKeyReceiver = null;
}
}
/**
* Home键监听内部类
*/
class SystemKeyReceiver extends BroadcastReceiver {
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();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
//Log.v(TAG, "---onReceive=---reason:" + reason);
if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {//短按Home键
if(mOnSystemKeyListener != null){
mOnSystemKeyListener.onHomeKey();
}
} else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {//最近任务键
if(mOnSystemKeyListener != null){
mOnSystemKeyListener.onRecentApps();
}
} else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {//锁屏
} else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {//samsung长按Home键
}
}
}
}
}