我最近在我的 Android 应用程序中实现了 Room。 (https://developer.android.com/training/data-storage/room)
它在 Activity
中运行良好。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWritedSMSViewModel = new ViewModelProvider(this).get(WritedSMSViewModel.class);
mWritedSMSViewModel.getAllWritedSMSs().observe(this, new Observer<List<WritedSMS>>() {
@Override
public void onChanged(@Nullable final List<WritedSMS> smss) {
// Update the cached copy of the words in the adapter.
if(smss != null) {
mAdapter.setSMSs(smss);
}
}
});
但是我无法使用 BroadcastReciever
中的 Room
mWritedSMSViewModel = new ViewModelProvider(???).get(WritedSMSViewModel.class);
问题是我不知道上面的代码应该使用什么参数。
我确认 this
和 context
不能用作参数。
我这是怎么了?
最佳答案
You shouldn't do that. It's bad practice. Because ViewModels only attached with
Activity
andFragment
Only.
有一件事可以满足您的要求。
在单独的 singleton
类中将 Room DB
操作与 ViewModel
分开。在 ViewModel 和任何其他需要的地方使用它。当接收到Broadcast
时,通过这个单例类而不是ViewModel将数据写入DB。
如果您正在观察 Fragment
中的 LiveData
,那么它也会更新您的 View 。
关于android - 如何在广播接收器中访问MyViewModel(AndroidViewModel),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905709/