Android Lifecycle使用

引言

Lifecycle 是官方提供的架构组件之一,目前已经是稳定版本,Lifecycle 组件包括LifecycleOwner、LifecycleObserver。Lifecycle 组件是执行操作以响应另一个组件(Activity或者Fragment)的生命周期状态的更改。 Lifecycle 生成更易于组织、更轻量级,更易于维护的代码。

不使用Lifecycle

在使用MVP模式中,如果需要Presenter感知Activity或者Fragment的生命周期,传统做法是Presenter中定义多个和Activity或者Fragment相应的生命周期方法,然后在Activity或者Fragment中调用Presenter中定义的方法,例如:

class UserPresenter(view: IUserView) {
    private val mView = view
    private val mModel: UserModel = UserModel()

    fun onStart(){
        // 初始化一些信息
    }

    fun onDestroy(){
        // 释放一起请求
    }
}
class MainActivity : AppCompatActivity(), IUserView {

    private val userPresenter = UserPresenter(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
        }

    }

    override fun onStart() {
        super.onStart()
        userPresenter.onStart()
    }

    override fun onDestroy() {
        super.onDestroy()
        userPresenter.onDestroy()
    }

    override fun onLoading() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onSuccess() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onComplete() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

实际项目中,需求可能比较复杂,这样会导致太多类似的调用,而使onStart()和onDestroy() 方法变的非常臃肿。

使用Lifecycle

定义IPresenter 接口类,继承LifecycleObserver ,其它具体的Presenter继承该类,方便使用。

interface IPresenter : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart(owner: LifecycleOwner)

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

定义一个具体的UserPresenter,继承IPresenter

class UserPresenter(view: IUserView) : IPresenter {
    private val mView = view
    private val mModel: UserModel = UserModel()

    companion object {
        const val TAG: String = "UserPresenter"
    }

    override fun onStart(owner: LifecycleOwner) {
        Log.d(TAG,"onStart and Presenter")
    }

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

在Activity或者Fragment使用

class MainActivity : AppCompatActivity(), IUserView {

    companion object {
        val TAG: String = "MainActivity"
    }

    private val userPresenter = UserPresenter(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                .replace(R.id.container, MainFragment.newInstance())
                .commitNow()
        }
        lifecycle.addObserver(userPresenter)// 订阅事件
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG,"onStart and UI")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG,"onDestroy and UI")
    }

    override fun onLoading() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onSuccess() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onComplete() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

运行查看下日志

2018-12-15 12:39:50.715 2679-2679/com.fomin.arch D/MainActivity: onStart and UI
2018-12-15 12:39:50.715 2679-2679/com.fomin.arch D/UserPresenter: onStart and Presenter
2018-12-15 12:39:53.876 2679-2679/com.fomin.arch D/UserPresenter: onDestroy and Presenter
2018-12-15 12:39:53.877 2679-2679/com.fomin.arch D/MainActivity: onDestroy and UI

这样Presenter 感知Activity或Fragment的生命周期已经实现,在Activity或Fragment生命周期变化会及时通知到Presenter。无需再Activity或Fragment实现相关Presenter的生命周期感知事件,减少维护成本。

Lifecycle原理

首先了解下Lifecycle组件主要有下面一些关键类

  • LifecycleObserver :实现该接口的类,通过注解的方式,可以通过被LifecycleOwner类的addObserver方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner的生命周期事件
  • LifecycleOwner:实现该接口的类持有生命周期(Lifecycle对象),该接口的生命周期(Lifecycle对象)的改变会被其注册的观察者LifecycleObserver观察到并触发其对应的事件
  • Event:从框架和Lifecycle类派发的生命周期事件
  • State?:由Lifecycle对象跟踪的组件的当前状态
  • LifecycleRegistry:负责控制state的转换、接受分发event事件

已Activity为例,会发现在SupportActivity里面继承了LifecycleOwner,持有LifecycleRegistry类,并且在getLifecycle()返回LifecycleRegistry类,方便继承类使用该类。

@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    @Override
    @SuppressWarnings("RestrictedApi")
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }

    @CallSuper
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveInstanceState(outState);
    }

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

而在业务Activity中需要lifecycle.addObserver(LifecycleObserver)订阅事件,这样就可以生效订阅/通知事件。Event分发是通过哪里进行分发的呢?可以看下ReportFragment.injectIfNeededIn(this)这句代码,ReportFragment对各个状态使用dispatch进行事件分发,然后调用LifecycleRegistry.handleLifecycleEvent,其接受到分发的Event从而改变State。

ReportFragment代码片段
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
     (Lifecycle.Event.ON_CREATE);
}

@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    dispatch(Lifecycle.Event.ON_START);
}

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}

@Override
public void onPause() {
    super.onPause();
    dispatch(Lifecycle.Event.ON_PAUSE);
}

@Override
public void onStop() {
    super.onStop();
    dispatch(Lifecycle.Event.ON_STOP);
}

@Override
public void onDestroy() {
    super.onDestroy();
    dispatch(Lifecycle.Event.ON_DESTROY);
    // just want to be sure that we won't leak reference to an activity
    mProcessListener = null;
}

private void dispatch(Lifecycle.Event event) {
    Activity activity = getActivity();
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}

LifecycleRegistry代码片段
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}

private void moveToState(State next) {
    if (mState == next) {
        return;
    }
    mState = next;
    if (mHandlingEvent || mAddingObserverCounter != 0) {
        mNewEventOccurred = true;
        // we will figure out what to do on upper level.
        return;
    }
    mHandlingEvent = true;
    sync();
    mHandlingEvent = false;
}
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
private void sync() {
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                + "new events from it.");
        return;
    }
    while (!isSynced()) {
        mNewEventOccurred = false;
        // no need to check eldest for nullability, because isSynced does it for us.
        if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
            backwardPass(lifecycleOwner);
        }
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if (!mNewEventOccurred && newest != null
                && mState.compareTo(newest.getValue().mState) > 0) {
            forwardPass(lifecycleOwner);
        }
    }
    mNewEventOccurred = false;
}

可以看下官方的对整个生命周期流动的解释

在该Lifecycle组件中,与传统的生命周期不同,只定义了五种状态,分别是:

  • INITIALIZED 最初始的状态
  • DESTROYED
  • CREATED
  • STARTED
  • RESUMED

上图中向右的箭头很好理解,每过来一个event会发生生命周期状态的变更,向左的箭头可以看成状态的回滚, 如果在RESUMED状态发生了ON_PAUSE事件,则状态回滚到STARTED状态;STARTED状态发生了ON_STOP事件,则回滚到CREATED状态。

总结

需要注意了是,在继承LifecycleObserver 时,官方建议使用DefaultLifecycleObserver ,因为随着Java8成为主流,将不会再使用注解方式,DefaultLifecycleObserver是需要另外声明的java8,并且最低API24才能build success。而GenericLifecycleObserver,FullLifecycleObserver,DefaultLifecycleObserver 这三个接口都是直接或者间接继承的LifecycleObserver。

// java8的lifecycle引用
implementation "android.arch.lifecycle:common-java8:1.1.1"
// 注解方式lifecycle引用
implementation 'android.arch.lifecycle:extensions:1.1.1'

Lifecycle使用,保持 UI 控制器(Activity 和 Fragment)尽可能的精简,更易复用,同时和LiveDataViewModel等使用更具有最佳实战。

原文地址:https://www.cnblogs.com/fomin/p/10124835.html

时间: 2024-10-21 06:47:54

Android Lifecycle使用的相关文章

Android Lifecycle

1. Bundle savedInstanceState it is not persist. it does not share between activities, it is nolyfor one activity. it is saved for soft kill like: 1.  orientation changes 2. when the process is killed by android due to low memory hard kill like: 1. fi

Android程序员必备精品资源 工具类

平时写程序中不断收集到的一些比较常用的东西,分享给大家. 实用工具集锦 Android Lifecycle https://github.com/xxv/android-lifecycle TinyPNG https://tinypng.com/ Android Layout Finder Android Layout Finder Android Asset Studio http://romannurik.github.io/AndroidAssetStudio/ JSON Validato

开发者必备的十二大Android开发资源

开发者必备的十二大Android开发资源 摘要: 论你是经验丰富的专业Android开发者,还是初出茅庐的新人,开发应用最忌讳的就是闭门造车.不能把自己圈在自己的思维里,要学会借助外在现有的资源去协助开发,这样既不会让自己固步自封,还能够提高工作效率. ... 无论你是经验丰富的专业Android开发者,还是初出茅庐的新人,开发应用最忌讳的就是闭门造车.不能把自己圈在自己的思维里,要学会借助外在现有的资源去协助开发,这样既不会让自己固步自封,还能够大大提高工作效率.在这里,本文介绍的这些资源包括

分享:Android程序员,必备精品网站大汇总

实用工具集锦 Android Lifecycle https://github.com/xxv/android-lifecycle Safe.ijiami http://safe.ijiami.cn/ TinyPNG https://tinypng.com/ Android Layout Finder Android Layout Finder Android Asset Studio http://romannurik.github.io/AndroidAssetStudio/ JSON Va

围观:开发者不容错过的十二大Android开发资源

摘要:无论你是初出茅庐的新人,还是富有经验的Android开发者,最忌讳的就是闭门造车,作为一个开发者,不能把自己圈在自己的思维模式中,要学会借助外界的资源去协助自己,以助于提高自己的工作效率. 借着周一这个新一周工作的开始,DEV资讯小编在这里给各位Android开发者介绍的资源包括工具.库和网站等.有效地利用它们,将有助于减轻我们的工作量,提高我们的工作效率. 1.OkHttp OkHttp是Square的一款产品,是一个Java的开源HTTP和SPDY客户端开发包,支持Android.An

activity 生命周期 http://stackoverflow.com/questions/8515936/android-activity-life-cycle-what-are-all-these-methods-for

331down voteaccepted See it in Activity Lifecycle (at Android Developers). onCreate(): Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also pr

Android -- Activity,Fragment lifecycle

Activity Lifecyce Fragment Lifecycle: 程序运行: 09-16 13:59:22.883 19022-19022/com.example.android.architecture.blueprints.todomvp.mock D/TasksActivity --debug: onCreate109-16 13:59:22.903 19022-19022/com.example.android.architecture.blueprints.todomvp.m

Android官方架构组件:Lifecycle详解&amp;迪士尼彩乐园网站架设原理分析

我们先将重要的这些类挑选出来: LifecycleObserver接口( Lifecycle观察者):实现该接口的类,通过注解的方式,可以通过被LifecycleOwner类的addObserver(LifecycleObserver o)方法注册,被注册后,LifecycleObserver便可以观察到LifecycleOwner的生命周期事件. LifecycleOwner接口(Lifecycle持有者):实现该接口的类持有生命周期(Lifecycle对象),该接口的生命周期(Lifecyc

Android官方架构组件:Lifecycle详解&amp;迪士尼彩乐园平台搭建原理分析

在过去的谷歌IO大会上,Google官方向我们推出了 Android Architecture Components,其中谈到Android组件处理生命周期的问题,向我们介绍了 Handling Lifecycles. 同时,如何利用 android.arch.lifecycle 包提供的类来控制数据.监听器等的 lifecycle.同时,LiveData 与 ViewModel 的 lifecycle 也依赖于 Lifecycle 框架. 经过公司内部的技术交流小组的探讨后,不少小伙伴觉得这个