如何在服务中初始化 viewModel。在片段中,我们使用 Kotlin 委托“by activityViewModels”进行初始化。或者我们可以使用 ViewModelProvider().get 进行初始化。但是据我所知,我们无法在服务中这样做,因为我们需要像活动或片段一样的“ViewModelStoreOwner”。
那么在服务中初始化 ViewModel 是最佳实践吗?
如何在服务中初始化 viewModel。在片段中,我们使用 Kotlin 委托“by activityViewModels”进行初始化。或者我们可以使用 ViewModelProvider().get 进行初始化。但是据我所知,我们无法在服务中这样做,因为我们需要像活动或片段一样的“ViewModelStoreOwner”。
那么在服务中初始化 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);
}
}
}