[Android][Jetpack] Lifecycle的基本使用

Lifecycle是什么

Lifecycle是Jetpack提供的一个组件,可以感知Activity,Fragment的生命周期变化。

简单使用

定义一个类继承自LifecycleObserver,根据业务需要,在这个类中重写相应的方法

public class LifecycleObserverImpl implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        Log.d(MainActivity.TAG, "onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        Log.d(MainActivity.TAG, "onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.d(MainActivity.TAG, "onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.d(MainActivity.TAG, "onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        Log.d(MainActivity.TAG, "onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Log.d(MainActivity.TAG, "onDestroy");
    }

}

在Activity中使用

public class LifeCycleActivity extends AppCompatActivity {

    LifecycleObserverImpl observer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle);
        //实例化
        observer = new LifecycleObserverImpl();
        //添加observer
        getLifecycle().addObserver(observer);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除observer
        getLifecycle().removeObserver(observer);
    }
}

这样,当Activity的生命周期变化时,我们自定义的observer就可以获取到变化。

运行应用,输出日志如下:

2020-04-14 11:08:06.579 22908-22908/com.wangyz.jetpack D/Jetpack: onCreate
2020-04-14 11:08:06.580 22908-22908/com.wangyz.jetpack D/Jetpack: onStart
2020-04-14 11:08:06.584 22908-22908/com.wangyz.jetpack D/Jetpack: onResume
2020-04-14 11:08:11.350 22908-22908/com.wangyz.jetpack D/Jetpack: onPause
2020-04-14 11:08:11.711 22908-22908/com.wangyz.jetpack D/Jetpack: onStop
2020-04-14 11:08:11.713 22908-22908/com.wangyz.jetpack D/Jetpack: onDestroy

一个最简单的Demo就写好了。

上一篇:vue双向绑定原理


下一篇:广播