View
?或?Activity
?上下文。如果?ViewModel
?存在的时间比 activity 更长(在配置更改的情况下),activity 将泄漏并且不会获得垃圾回收器的妥善处置。可以根据原则进行实战啦 。
自定义LifecycleOwner
public class MyActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry lifecycleRegistry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lifecycleRegistry = new LifecycleRegistry(this);
lifecycleRegistry.markState(Lifecycle.State.CREATED);
}
@Override
public void onStart() {
super.onStart();
lifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return lifecycleRegistry;
}
}