Android Jetpack -- Lifecycle

看到这些博客的时候,相信小伙伴们已经看了不少的有关于Android Jetpack的知识了,关于Jetpack的原理,有些文章讲的很好,这里就不重复了,此系列的博客,旨在通过一些很简单的小demo,和大家一起熟悉最基本的用法~

Android Jetpack -- Lifecycle

Android Jetpack -- ViewModel & LiveData

Android Jetpack -- paging & room

Android Jetpack -- navigation

项目git地址:https://github.com/zhangtiansimple/jetpack_demo

--------------------------------------------------------------------------------------------------------------------

先来看一个小栗子

有一个Presenter

class Presenter {

    fun create() {
        //TODO
    }

    fun destroy() {
        //TODO
    }
}

然后在Activity里

class MainActivity(val presenter: Presenter) : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        presenter.create()
    }

    override fun onDestroy() {
        super.onDestroy()

        presenter.destroy()
    }
}

这样写本身是没有问题的,但是随着业务逻辑的不断增多,越来越多的初始化及回收操作需要在onCreate和onDestory中完成,会导致这两个方法变得非常臃肿。

Lifecycle便应时而生,Lifecycle持有组件(Activity、Fragment等)的生命周期的状态信息,并且允许其他对象观察此状态。

而且实现也很简洁

首先定义IPresenter接口

interface IPresenter : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy(owner: LifecycleOwner)

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    fun onLifecycleChanged(
        owner: LifecycleOwner,
        event: Lifecycle.Event
    )
}

然后把想要观察到的声明周期事件封装到BasePresenter里

open class BasePresenter : IPresenter {

    val TAG = "BasePresenter"

    override fun onCreate(owner: LifecycleOwner) {
        Log.d(TAG, "onCreate")
    }

    override fun onDestroy(owner: LifecycleOwner) {
        Log.d(TAG, "onDestroy")
    }

    override fun onLifecycleChanged(owner: LifecycleOwner, event: Lifecycle.Event) {
    }
}

如此,每当MainActivity发生了对应的生命周期改变,MainPresenter就会执行对应事件注解的方法

class MainPresenter : BasePresenter() {

    override fun onCreate(owner: LifecycleOwner) {
        Log.e(TAG, "MainPresenter onCreate");
        super.onCreate(owner)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        Log.e(TAG, "MainPresenter onDestroy");
        super.onDestroy(owner)
    }
}
class MainActivity : AppCompatActivity() {

    private val TAG = "MainActivity"
    private var mPresenter: IPresenter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.e(TAG, "MainActivity onCreate")
        mPresenter = MainPresenter()
        getLifecycle().addObserver(mPresenter as MainPresenter);
    }

    override fun onDestroy() {
        Log.e(TAG, "MainActivity onDestroy")
        super.onDestroy()
    }
}

这里只实现了onCreate和onDestroy,需要求他的生命周期状态时,只需要实现对应的方法。

 

接下来看看原理,掌握Liifecycle,首先要理解五个类

LifeCycleObserver接口(Lifecycle观察者):实现该接口的类,可以用过lifecyclerowner类的addObserver()方法进行注册,之后,lifecycleObserver便可以观察到lifeCycleOwner中的生命周期事件。

LifeCycleOwner接口(LifeCycle的持有者):实现该接口的类持有lifecycle对象,该类的声明周期周期发生变化时,会被注册的观察者也就是LifeCycleObsverser观察到。

LifeCycle(生命周期)

State(当前声明周期所处的状态)

Event(当前声明周期改变对应的事件)

Activity与Fragment实现机制类似,这里来看看Activity的实现

public class ComponentActivity extends Activity
        implements LifecycleOwner, KeyEventDispatcher.Component {
    

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

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

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

getLifecycle()方法实际返回的是LifeCycleRegistry对象,我们在来看LifeCycleRegistry类

public class LifecycleRegistry extends Lifecycle {
}

LifeCycleRegistry是LifeCycle的子类

public abstract class Lifecycle {

        //注册LifecycleObserver (比如Presenter)
        public abstract void addObserver(@NonNull LifecycleObserver observer);
        //移除LifecycleObserver 
        public abstract void removeObserver(@NonNull LifecycleObserver observer);
        //获取当前状态
        public abstract State getCurrentState();

        public enum Event {
            ON_CREATE,
            ON_START,
            ON_RESUME,
            ON_PAUSE,
            ON_STOP,
            ON_DESTROY,
            ON_ANY
        }
        
       public enum State {
            DESTROYED,
            INITIALIZED,
            CREATED,
            STARTED,
            RESUMED;

            public boolean isAtLeast(@NonNull State state) {
                return compareTo(state) >= 0;
            }
       }
}

lifeCycle里的抽象方法在LifeCycleRegistry里进行了实现,LifeCycleRegistry中有一个方法

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

handleLifecycleEvent方法会通过 getStateAfter 获取当前应处的状态并修改 Lifecycle本身的State 值,紧接着遍历所 LifecycleObserver 并同步且通知其状态发生变化,因此就能触发LifecycleObserver 对应的生命周期事件。

你可能感兴趣的:(你好,Android)