The situation:
Upon receiving an SMS, the MyReceiver
class extracts the SMS and should then use a ViewModel
object to insert data into a database.
The documentation focuses on instantiation from a class extending AppCompatActivity
, but is it necessary to pass an existing activity's ownership to the ViewModelProvider
constructor?
The problem: Getting access to a ViewModel Object from a public class (not an activity).
public class MyReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent){
mMyViewModel = new ViewModelProvider(??).get(MyViewModel.class);
}
}
Attempted solutions:
In order to pass this
to the ViewModelProvider
constructor I tried to make MyReceiver
implement androidx.lifecycle.ViewModelStoreOwner
. This requires overriding the method getViewModelStore
. But I do not understand what a ViewModelStore is or how to create it to return a ViewModel.
@NonNull
@Override
public ViewModelStore getViewModelStore(){
return ??;
}
Any help would be greatly appreciated.