序言
将Livedata在广播中进行使用,这样当广播消息,使用Livedata进行观察获取消息,不需要在Activity里面注册广播了,特别适合在多个Activity里面都要监听一个广播的需求。
项目需求
现在有一个手表连接的广播,当手表连接状态改变时,有多个Activity需要获取到这个手表改变的状态,然后根据状态进行相应的处理。
功能实现
首先在Application
里面
override fun onCreate() {
super.onCreate()
instance = this
br = WatchConnectLiveData.getInstance()
}
override fun onTerminate() {
br.unRegisterReceiver()
super.onTerminate()
}
@SuppressLint("StaticFieldLeak")
companion object {
@SuppressLint("StaticFieldLeak")
private lateinit var instance: MyApplication
fun getInstance(): MyApplication {
return instance
}
private lateinit var br: WatchConnectLiveData
fun getBroadcastLiveData(): WatchConnectLiveData {
return br
}
}
我们创建WatchConnectLiveData
类,继承LiveData文章来源:https://www.toymoban.com/news/detail-531746.html
public class WatchConnectLiveData extends LiveData<Integer> {
private static WatchConnectLiveData instance;
private BroadcastReceiver broadcastReceiver;
public synchronized static WatchConnectLiveData getInstance() {
if (instance == null) {
instance = new WatchConnectLiveData();
}
return instance;
}
private WatchConnectLiveData() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
int state = intent.getIntExtra("state", -1);
Log.e("手表连接状态", "此时状态为:" + state);
postValue(state);
}
}
};
// 注册广播接收器
registerReceiver();
}
@Override
protected void onActive() {
Log.e("TAG", "当有观察者时调用此方法");
if (broadcastReceiver == null) {
registerReceiver();
}
}
@Override
protected void onInactive() {
Log.e("TAG", "观察者没了");
}
private void registerReceiver() {
// 注册广播接收器
IntentFilter intentFilter = new IntentFilter("com.xxxxx.xxxxx.action.CONNECTION_STATE_CHANGED");
MyApplication.Companion.getInstance().registerReceiver(broadcastReceiver, intentFilter);
}
public void unRegisterReceiver() {
if (broadcastReceiver != null) {
MyApplication.Companion.getInstance().unregisterReceiver(broadcastReceiver);
broadcastReceiver = null;
}
}
}
这样在程序启动的时候,我们就创建了一个全局的观察者,当此广播有数据发生变化的时候,我们就可以通过livedata进行获取到状态的改变文章来源地址https://www.toymoban.com/news/detail-531746.html
MyApplication.getBroadcastLiveData().observe(viewLifecycleOwner) {
Log.e(TAG, "状态===>>> $it <<<===")
//根据相应的状态进行数据处理和操作
}
到了这里,关于【Android】LiveData在广播中的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!