一、程式碼實現如下
/**
* @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()
方法開啟監聽。