【发布时间】:2018-09-13 22:22:19
【问题描述】:
在我的应用程序中,我需要通过 BroadcastReceiver 在我的数据库中添加/删除/更新数据。我想知道这方面的最佳做法是什么。由于 onReceive 是在主线程上调用的,因此我需要一种在工作线程上运行查询的方法,并且在完成时我需要 onReceive 方法中的响应。
为此,我使用了这样一个简单的观察者模式。
public class NetworkChangeReceiver extends BroadcastReceiver implements IDbUpdateListener{
private MyRepository repo;
private Application application;
@Override
public void onReceive(Context context, Intent intent) {
//Some conditions
//Initializing and setting listener for repo
respo = new MyRepository(this); //this is the listener interface
repo.getAllContents();
}
}
}
//Interface method implemented
@Override
public void onDbUpdate(Content content) {
//Do something with the data
}
}
我将侦听器传递给我在侦听器上调用 onDbUpdate() 方法的存储库,从而在接收器中获得响应。
如果它是一个活动/片段而不是广播接收器,我会简单地使用带有实时数据的 viewModel 作为可观察对象,在我的活动中,我会观察 viewmodel 是否有这样的变化
mViewModel.getAllContent().observe(this, new Observer<List<Content>>() {
@Override
public void onChanged(@Nullable final List<Content> contents) {
// Do something
}
});
我的方法是否可行,或者在 BroadcastReceiver 中是否有明显更好的方法来实现这一点?谢谢!!
【问题讨论】:
-
您需要更新视图还是只需要在后台运行?而且我还可以看到你需要在有网络时运行它吗?
-
@PaulOkeke 不,在这种情况下我不需要更新任何视图。每当触发相应的广播意图时,我希望它在后台运行。是啊,你说得对。我需要在有网络时运行它。您有更好的方法吗?主要问题是在数据库查询或改造调用等异步任务完成后得到通知。在视图中,这很容易通过 ViewModel 实现,但我想知道非 UI 类将如何监听这些事件,因为我相信将 ViewModel 与广播接收器一起使用是一种反模式。
-
请使用 WorkManager。 developer.android.com/topic/libraries/architecture/workmanager/…。这样你就不一定需要自己监听网络状态。 WorkMananger 可以根据您为其运行设置的
Constraints来处理。 -
@PaulOkeke 看起来很有趣,我之前没遇到过。肯定会读到这一点。谢谢!!
标签: android observer-pattern android-room android-mvvm