如何在服务中初始化视图模型。在一个片段中,我们用Kotlin委托">by activityViewModels";。或者我们可以使用ViewModelProvider((.get。但据我所知,我们不能在服务中做到这一点,因为我们需要一个">ViewModelStoreOwner";如活性或片段。
那么,这是在服务中初始化ViewModel的最佳实践吗?
我在这里的项目。
不建议在服务中使用ViewModel。您可以从服务本身调用存储库。
https://github.com/android/architecture-components-samples/issues/137#issuecomment-327854042
ViewModel应与Activity或Fragment紧密结合使用,所以它注定要存在于应用程序的UI层中。因此,我不建议在服务中使用ViewModel。创造一个不同的类,将在服务中使用,如果需要,在ViewModel中。像这样,您可以确保关注点和避免赋予ViewModel超出需要的职责。
定义一个基本服务,然后可以使用类似ViewModel的活动/片段
public class LifecycleAndViewStoreOwnerService extends LifecycleService implements ViewModelStoreOwner, HasDefaultViewModelProviderFactory {
final ViewModelStore mViewModelStore = new ViewModelStore();
ViewModelProvider.Factory mFactory;
@NonNull
@Override
public ViewModelStore getViewModelStore() {
return mViewModelStore;
}
@Override
public void onCreate() {
super.onCreate();
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
if (source.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
mViewModelStore.clear();
source.getLifecycle().removeObserver(this);
}
}
});
}
@NonNull
@Override
public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
return mFactory != null ? mFactory : (mFactory = new ViewModelProvider.AndroidViewModelFactory(getApplication()));
}
}
扩展上述类,在服务中显示覆盖窗口
public class MyLifecycleService extends LifecycleAndViewStoreOwnerService {
private static final String TAG = "MyLifecycleService";
@Override
public void onCreate() {
super.onCreate();
final OverlayWindowBinding binding = OverlayWindowBinding.inflate(LayoutInflater.from(this));
binding.setViewModel(new ViewModelProvider(this).get(ViewModel.class));
binding.setLifecycleOwner(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
getSystemService(WindowManager.class).addView(binding.getRoot(), layoutParams);
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
if (source.getLifecycle().getCurrentState() == Lifecycle.State.DESTROYED) {
getSystemService(WindowManager.class).removeViewImmediate(binding.getRoot());
source.getLifecycle().removeObserver(this);
}
}
});
}
public static class ViewModel extends AndroidViewModel {
public ViewModel(@NonNull Application application) {
super(application);
}
}
}