使用LiveData我们不需要管理广播的生命周期,下面我们就使用LiveData来实现监听广播,当我们需要监听广播时只要实例化该对象,传入想要监听的广播比如解锁(Intent.ACTION_SCREEN_ON) 锁屏 (Intent.ACTION_SCREEN_OFF)
- 具体代码如下
public class SystemActionLiveData extends LiveData<String> {
private Context mContext;
private IntentFilter intentFilter;
/** 广播监听器 */
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null || action.isEmpty()) {
return;
}
setValue(action);
}
};
/**
* 构造函数
*
* @param context {@link Context}
* @param actions 需要监听的Action {@link Intent#ACTION_XXX}
*/
public SystemActionLiveData(Context context, String... actions) {
mContext = context;
intentFilter = new IntentFilter();
for (String action : actions) {
intentFilter.addAction(action);
}
}
@Override
protected void onActive() {
super.onActive();
if (mContext != null) {
mContext.registerReceiver(mReceiver, intentFilter);
}
}
@Override
protected void onInactive() {
super.onInactive();
if (mContext != null) {
mContext.unregisterReceiver(mReceiver);
}
}
}
- 使用方式
new SystemActionLiveData(this, Intent.ACTION_SCREEN_ON, Intent.ACTION_SCREEN_OFF)//
.observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String action) {
switch (action) {
case Intent.ACTION_SCREEN_ON:
break;// 开屏
case Intent.ACTION_SCREEN_OFF:
break;// 锁屏
}
}
});
- 注意记得加入权限