Broadcast Receiver中如何访问MyViewModel(AndroidViewModel)

How to access MyViewModel(AndroidViewModel) in Broadcast Receiver

我最近在我的 android 应用中实现了 Room。 (https://developer.android.com/training/data-storage/room)

它在 Activities 中运行良好。

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

中的房间
mWritedSMSViewModel = new ViewModelProvider(???).get(WritedSMSViewModel.class);

问题是我不知道上面的代码应该使用什么参数。 我确认 thiscontext 不能用作参数。

我怎么了?

You shouldn't do that. It's bad practice. Because ViewModels only attached with Activity and Fragment Only.

有可能达到您的要求。

在单独的 singleton class 中将您的 Room DB 操作与 ViewModel 分开。在 ViewModel 和任何其他需要的地方使用它。当收到Broadcast时,通过这个单例class而不是ViewModel将数据写入DB。

如果您正在观察 Fragment 中的 LiveData,那么它也会更新您的观点。