一、代码实现如下
/**
* @author 郭翰林
* @date 2018/10/31 0031 10:04
* 注释: 锁屏按钮和Home键监听
*/
public class ScreenBroadcastReceiver extends BroadcastReceiver {
private static volatile ScreenBroadcastReceiver instance;
private boolean isReceiver;
/**
* 注释:获取单例
* 时间:2018/10/31 0031 14:46
* 作者:郭翰林
*
* @return
*/
public static ScreenBroadcastReceiver getInstance() {
synchronized (ScreenBroadcastReceiver.class) {
if (instance == null) {
instance = new ScreenBroadcastReceiver();
}
return instance;
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
UmsAgent.postHistoryLog(SysApplication.getInstance());
}
}
/**
* 注释:注册屏幕监听广播
* 时间:2018/10/31 0031 10:05
* 作者:郭翰林
*/
public void registerScreenReceive(Context context) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
if (!isReceiver) {
isReceiver = true;
context.registerReceiver(instance, filter);
}
}
/**
* 注释:取消注册屏幕监听广播
* 时间:2018/10/31 0031 10:05
* 作者:郭翰林
*/
public void unregisterScreenReceive(Context context) {
if (isReceiver && instance != null) {
isReceiver = false;
context.unregisterReceiver(instance);
}
}
}
复制代码
二、使用方式
ScreenBroadcastReceiver.getInstance().registerScreenReceive(SysApplication.getInstance());
复制代码
这里有几个注意点:
- Context传递
applicationcontext
,因为是单例,避免内存释放不了,引起不必要的BUG - 只需在应用启动页的
onCreate()
方法中使用调用一次即可 unregisterScreenReceive()
反注册可调可不调,调用一次之后监听取消,再次调用registerScreenReceive()
方法开启监听。