我正在构建一个位置应用程序,在主活动中显示来自房间数据库的背景位置。我可以通过调用
locationViewModel = ViewModelProviders.of(this).get(LocationViewModel.class);
locationViewModel.getLocations().observe(this, this);
当我通过广播接收器接收位置更新时,应将定期的背景位置保存到房间数据库中。应该打电话救他们
locationViewModel.getLocations().setValue()
public class LocationUpdatesBroadcastReceiver extends BroadcastReceiver {
static final String ACTION_PROCESS_UPDATES =
"com.google.android.gms.location.sample.backgroundlocationupdates.action" +
".PROCESS_UPDATES";
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_PROCESS_UPDATES.equals(action)) {
LocationResult result = LocationResult.extractResult(intent);
if (result != null) {
List<Location> locations = result.getLocations();
List<SavedLocation> locationsToSave = covertToSavedLocations(locations)
//Need an instance of LocationViewModel to call locationViewModel.getLocations().setValue(locationsToSave)
}
}
}
}
}
问题是,我应该如何获取像这个广播接收器这样的非活动类中的locationViewModel实例?打电话对吗
locationViewModel = ViewModelProviders.of(context).get(LocationViewModel.class)
其中context是我从中接收的context
onReceive (Context context, Intent intent)
广播接收器的?
获取viewmodel后,是否需要使用
LiveData.observeForever
和
LiveData.removeObserver
因为广播接收器不是生命周期所有者?