Lifecycle是什么
是Jetpack提供的一个组件;可以感知Activity、Fragment生命周期变化。
使用
自定义LifecycleObserver
public class LifecycleObserverImpl implements LifecycleObserver {
private static final String TAG = "Lifecycle-";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d(TAG, "onCreate: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d(TAG, "onStart: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d(TAG, "onResume: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d(TAG, "onPause: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d(TAG, "onStop: ");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
}
}
在Activity使用
public class MainActivity2 extends AppCompatActivity {
private LifecycleObserverImpl observer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
observer = new LifecycleObserverImpl();
getLifecycle().addObserver(observer);
}
@Override
protected void onDestroy() {
super.onDestroy();
getLifecycle().removeObserver(observer);
}
}
原理
Lifecycle感知生命周期变化,通知observer。getLifecycle().addObserver(observer)。调用了FragmentActivity的getLifecycle()--》ComponentActivity的getLifecycle() 最终返回mLifecycleRegistry。
将observer和state组装微ObserverWithState对象。ReflectiveGenericLifecycleObserver创建CallbackInfo信息,通过注解添加到map中。observer注册了Lifecycle.Event.ON_RESUME监听。调用invokeMethodsForEvent方法。最终是反射调用,通过addObserver,解析注解保存起来。
image.png
网友评论