欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android中Lifecycle的原理详解

程序员文章站 2022-02-02 09:45:17
目录一、基本使用二、lifecycleobserver接口和lifecycleowner接口三、getlifecycle()四、绑定生命周期总结lifecycle是android architectu...

        lifecycle是android architecture components的成员,是一个生命周期感知组件,能够感知activity、fragment等组件的生命周期变化,并将变化通知到已注册的观察者。正确的使用有助于更好地组织代码,减少内存泄漏,增强稳定。下面分析他的实现原理,看看到底只怎么感知生命周期的。

一、基本使用

1、引入依赖库

dependencies {
    def lifecycle_version = "2.5.0-alpha01"
    def arch_version = "2.1.0"
 
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
  
    implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
 
    implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
 
    //非java8使用
    annotationprocessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" 
    //java8使用
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"  
}

2、自定义一个类实现lifecycleobserver,在类中监听生命周期回调

public class basejsapi implements lifecycleobserver {
 
  
    @onlifecycleevent(lifecycle.event.on_create)
    void create() {
        oncreate();
    }
 
    @onlifecycleevent(lifecycle.event.on_destroy)
    void destroy() {
        ondestroy();
    }
 
 
    @onlifecycleevent(lifecycle.event.on_resume)
    void resume() {
        onresume();
    }
 
    @onlifecycleevent(lifecycle.event.on_pause)
    void pause() {
        onpause();
    }
 
    ……………………………………
 
  }

3、在activity或者fragment中注册。

 getlifecycle().addobserver(getjsbridge());

通过以上两步就可以感知当前activity的生命周期了,非常的简便实用。

二、lifecycleobserver接口和lifecycleowner接口

public interface lifecycleobserver {
 
}
 
public interface lifecycleowner {
  @nonnull
  lifecycle getlifecycle();
}

        lifecycleobserver是一个空接口,lifecycleowner提供getlifecycle返回lifecycle,该接口由componentactivity实现,提供了getlifecycle的实现。

三、getlifecycle()

        getlifecycle方法实际上是调用的componentactivity的getlifecycle方法,通过查看,activity确实也是继承的componentactivity,该方法返回mlifecycleregistry对象,该对象继承自lifecycle,具体实现了添加观察者,移出观察者的方法,还定义了一个生命周期的枚举。

public class lifecycleregistry extends lifecycle {
  
 
}
 
public abstract class lifecycle {
 
    @mainthread
    public abstract void addobserver(@nonnull lifecycleobserver observer);
 
    @mainthread
    public abstract void removeobserver(@nonnull lifecycleobserver observer);
 
    @mainthread
    @nonnull
    public abstract state getcurrentstate();
 
    public enum event {
       
        on_create,
       
        on_start,
        
        on_resume,
        
        on_pause,
        
        on_stop,
        
        on_destroy,
       
        on_any;
        …………………………………………
      }
      ………………………………
}

        也就可以看出getlifecycle().addobserver实际上就是执行lifecycleregistry的addobserver的方法添加观察者,做一个小总结如下:

观察者实现lifecycleobserver,实现需要的生命周期。在activity、fragment中添通过getlifecycle().addobserver加观察者。实际上调用的是componentactivity的getlifecycle方法返回mlifecycleregistry。调用lifecycleregistry的addobserver加观察者。三、添加观察者的流程

        详情看注释:

@override
public void addobserver(@nonnull lifecycleobserver observer) {
    //检查是否在主线程
    enforcemainthreadifneeded("addobserver");
    //设置状态值
    state initialstate = mstate == destroyed ? destroyed : initialized;
    //将观察者和初始化的值封装到observerwithstate中
    observerwithstate statefulobserver = new observerwithstate(observer, initialstate);
    //以观察者为key,statefulobserver为value放到hashmap集合中
    observerwithstate previous = mobservermap.putifabsent(observer, statefulobserver);
    //不为null表示之前已经放进去了,否则没放进去,放进去了就添加结束
    if (previous != null) {
        return;
    }
    //获取被观察者对象,即activity,如果被销毁了,则结束
    lifecycleowner lifecycleowner = mlifecycleowner.get();
    if (lifecycleowner == null) {
        // it is null we should be destroyed. fallback quickly
        return;
    }
 
    //maddingobservercounter 表示正在添加的观察者的数量,
    //开始添加新的observe之前,对该变量进行++操作,添加完成后,进行--操作。
    //mhandlingevent表示是否正在处理
    boolean isreentrance = maddingobservercounter != 0 || mhandlingevent;
    //计算状态,进行while循环
    state targetstate = calculatetargetstate(observer);
    maddingobservercounter++;
    //新添加的lifecycleobserver ,会不断更新自己的生命周期到指定的targetstate
    while ((statefulobserver.mstate.compareto(targetstate) < 0
            && mobservermap.contains(observer))) {
        //添加状态到list,计算当前状态,用于计算状态calculatetargetstate
        pushparentstate(statefulobserver.mstate);
        //
        final event event = event.upfrom(statefulobserver.mstate);
        if (event == null) {
            throw new illegalstateexception("no event up from " + statefulobserver.mstate);
        }
        //生命周期分发:分发到mlifecycleobserver里面
        statefulobserver.dispatchevent(lifecycleowner, event);
        //移除状态到list
        popparentstate();
        // mstate / subling may have been changed recalculate
        //重新计算状态
        targetstate = calculatetargetstate(observer);
    }
    //没有事件正在处理,或者是添加了observe,就需要重新同步一次状态,下面详细介绍
    if (!isreentrance) {
        // we do sync only on the top level.
        sync();
    }
    maddingobservercounter--;
}
//计算状态规则
private state calculatetargetstate(lifecycleobserver observer) {
    //在map中获取到当前observer的前一个observer
    map.entry<lifecycleobserver, observerwithstate> previous = mobservermap.ceil(observer);
    //前一个observer的state
    state siblingstate = previous != null ? previous.getvalue().mstate : null;
    //如果是嵌套添加observer,获取父级observer的状态
    state parentstate = !mparentstates.isempty() ? mparentstates.get(mparentstates.size() - 1)
            : null;
    //获取最小状态,destroyed < initialized < created < started < resumed
    return min(min(mstate, siblingstate), parentstate);
}

四、绑定生命周期

        上面介绍了addobserver的流程,在componentactivity的oncreate方法中:

reportfragment.injectifneededin(this);

        reportfragment是一个fragment,它负责分派生命周期的事件,injectifneededin()就是在当前的activity里添加一个reportfragment,和glide的绑定生命周期比较类似。

public static void injectifneededin(activity activity) {
    //当api>=29注册registerin绑定生命周期
    if (build.version.sdk_int >= 29) {
        // on api 29+, we can register for the correct lifecycle callbacks directly
        lifecyclecallbacks.registerin(activity);
    }
    android.app.fragmentmanager manager = activity.getfragmentmanager();
    if (manager.findfragmentbytag(report_fragment_tag) == null) {
        manager.begintransaction().add(new reportfragment(), report_fragment_tag).commit();
        // hopefully, we are the first to make a transaction.
        manager.executependingtransactions();
    }
}

         当api>=29是通过application.activitylifecyclecallbacks的方式注册生命周期, 以onstart为例,其他onresume、onpause等类似:

@override
public void onstart() {
    super.onstart();
    dispatchstart(mprocesslistener);
    dispatch(lifecycle.event.on_start);
}

         重点看看dispatch:

private void dispatch(@nonnull lifecycle.event event) {
    //当api<29分发dispatch绑定生命周期
    if (build.version.sdk_int < 29) {
        // only dispatch events from reportfragment on api levels prior
        // to api 29. on api 29+, this is handled by the activitylifecyclecallbacks
        // added in reportfragment.injectifneededin
        dispatch(getactivity(), event);
    }
}

        不管是pplication.activitylifecyclecallbacks还是当前fragment的生命周期方式都会执行如下dispatch:

static void dispatch(@nonnull activity activity, @nonnull lifecycle.event event) {
    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的handlelifecycleevent将生命周期分发出去,lifecycleregistry上面已经介绍过了addobserve逻辑了,代码比较长,只显示关键代码:

handlelifecycleevent -> movetostate -> sync

private void sync() {
    lifecycleowner lifecycleowner = mlifecycleowner.get();
    if (lifecycleowner == null) {
        throw new illegalstateexception("lifecycleowner of this lifecycleregistry is already"
                + "garbage collected. it is too late to change lifecycle state.");
    }
    //没有同步过,则同步
    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) {
            //如果observerwithstate的state小于当前state,那么就调用forwardpass方法,
            backwardpass(lifecycleowner);
        }
        map.entry<lifecycleobserver, observerwithstate> newest = mobservermap.newest();
        if (!mneweventoccurred && newest != null
                && mstate.compareto(newest.getvalue().mstate) > 0) {
            //如果大于当前state,那么就调用backwardpass方法。
            forwardpass(lifecycleowner);
        }
    }
    mneweventoccurred = false;
}

        backwardpass和forwardpass的代码都会调用:

observer.dispatchevent(lifecycleowner, event)

static class observerwithstate {
    state mstate;
    lifecycleeventobserver mlifecycleobserver;
 
    observerwithstate(lifecycleobserver observer, state initialstate) {
        mlifecycleobserver = lifecycling.lifecycleeventobserver(observer);
        mstate = initialstate;
    }
 
    void dispatchevent(lifecycleowner owner, event event) {
        state newstate = event.gettargetstate();
        mstate = min(mstate, newstate);
        mlifecycleobserver.onstatechanged(owner, event);
        mstate = newstate;
    }
}

        调用了lifecycling.getcallback方法来获得mlifecycleobserver的实例,通过这个实例调用onstatechanged:

static lifecycleeventobserver lifecycleeventobserver(object object) {
    boolean islifecycleeventobserver = object instanceof lifecycleeventobserver;
    boolean isfulllifecycleobserver = object instanceof fulllifecycleobserver;
    if (islifecycleeventobserver && isfulllifecycleobserver) {
        return new fulllifecycleobserveradapter((fulllifecycleobserver) object,
                (lifecycleeventobserver) object);
    }
    if (isfulllifecycleobserver) {
        return new fulllifecycleobserveradapter((fulllifecycleobserver) object, null);
    }
 
    if (islifecycleeventobserver) {
        return (lifecycleeventobserver) object;
    }
    //通过反射,找到lifecycle 自动生成的类
    final class<?> klass = object.getclass();
    int type = getobserverconstructortype(klass);
    if (type == generated_callback) {
        list<constructor<? extends generatedadapter>> constructors =
                sclasstoadapters.get(klass);
        if (constructors.size() == 1) {
            generatedadapter generatedadapter = creategeneratedadapter(
                    constructors.get(0), object);
            最终使用生成的adapter,创建singlegeneratedadapterobserver
            return new singlegeneratedadapterobserver(generatedadapter);
        }
        generatedadapter[] adapters = new generatedadapter[constructors.size()];
        for (int i = 0; i < constructors.size(); i++) {
            adapters[i] = creategeneratedadapter(constructors.get(i), object);
        }
        return new compositegeneratedadaptersobserver(adapters);
    }
    return new reflectivegenericlifecycleobserver(object);
}
class singlegeneratedadapterobserver implements lifecycleeventobserver {
 
    private final generatedadapter mgeneratedadapter;
 
    singlegeneratedadapterobserver(generatedadapter generatedadapter) {
        mgeneratedadapter = generatedadapter;
    }
 
    @override
    public void onstatechanged(@nonnull lifecycleowner source, @nonnull lifecycle.event event) {
        mgeneratedadapter.callmethods(source, event, false, null);
        mgeneratedadapter.callmethods(source, event, true, null);
    }
}

        到这里会根据依赖中添加的annotationprocessor "androidx.lifecycle:lifecycle-compiler:2.2.0"根据不同生命周期注解生成不同的类,整个过程还是比较复杂的。整体过程如下图:

Android中Lifecycle的原理详解

总结

到此这篇关于android中lifecycle的原理详解的文章就介绍到这了,更多相关android lifecycle原理内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Android Lifecycle