生命周期观察者LifecycleObserver

转载请注明出处:Write By xyx In cdsn @包罗万码

原文地址:https://blog.csdn.net/a316375/article/details/83051824

为了方便Activity的代码优化,Android推出了生命周期观察者,复杂活简单说,

先看代码:这是一个声明周期的观察者类;

public class MyObserver implements LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void ready(){
        Log.e("--LifecycleObserver","ON_START");
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void connectListener() {
        Log.e("--LifecycleObserver","ON_RESUME");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {
        Log.e("--LifecycleObserver","ON_PAUSE");
    }
}

在你的Activity中调用下面这句话 

getLifecycle().addObserver(new MyObserver());

啥个意思:就是把Activity中生命周期的方法延伸给另外一个类, 让另外一个类去处理生命周期的方法,缩小了Activity的代码量

Activity只负责绘制UI部分的代码

 

Activity部分你也可以这么写让它实现:LifecycleOwner

如果您要创建自定义类,则 LifecycleOwner可以使用 LifecycleRegistry  类,但需要将事件转发到该类,如以下代码示例所示:

说了那么多没看懂,LifecycleOwner啥个意思,既然他LifecycleObserver 是一个观察者,那么就可以用来注册观察者,LifecycleOwner通过 LifecycleRegistry 用来控制LifecycleObserver,

Activity中注释这个代码//getLifecycle().addObserver(new MyObserver());

public class WelcomeActivity extends AppCompatActivity implements LifecycleOwner {

   //...
    LifecycleRegistry lifecycleRegistry;
    private MyObserver myObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
       //...
        lifecycleRegistry = new LifecycleRegistry(this);
        myObserver = new MyObserver();

        lifecycleRegistry.addObserver(myObserver);
        lifecycleRegistry.markState(Lifecycle.State.CREATED);

       //...
    }

    @Override
    protected void onStart() {
        super.onStart();
        myObserver.disconnectListener();//通知者的断开连接,会直接跳到Activity的onPause方法()
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("--", "Activity---onPause: " );
        lifecycleRegistry.markState(Lifecycle.State.STARTED);//进入了Activity的StartED状态
    }

    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }
}

Lifecycle.State 跟 Lifecycle.Event今晚暂不更新解说

2018-10-14 22:59:28.315 21461-21461 /... E/--LifecycleObserver: ON_PAUSE
2018-10-14 22:59:28.316 21461-21461/....E/--LifecycleObserver: ON_START
2018-10-14 22:59:28.317 21461-21461/.... E/--LifecycleObserver: ON_RESUME
2018-10-14 22:59:28.343 21461-21461/.... E/--LifecycleObserver: ON_PAUSE
2018-10-14 22:59:28.343 21461-21461/..... E/--: Activity---onPause: 

 看到log里边,会直接进入Activity的onPause状态:

这个LifecycleOwner使得Activity的生命周期变成了可随意调整的状态模式

你可能感兴趣的:(生命周期观察者LifecycleObserver)