美文网首页
Lifecycle_原理解析

Lifecycle_原理解析

作者: 夏木友人 | 来源:发表于2022-10-08 18:48 被阅读0次

一、使用Lifecycle

1. 引入Lifecycle

我们来看一下如何引入:

1.非androidX项目引入:

//运行时
implementation "android.arch.lifecycle:runtime:1.1.1"
// 编译期
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

2.androidX项目引入:

implementation "androidx.lifecycle:lifecycle-runtime:2.0.0"
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
implementation "androidx.lifecycle:lifecycle-common-java8:2.0.0"
annotationProcessor  "androidx.lifecycle:lifecycle-compiler:2.0.0"

2. 创建生命周期观察者

我们首先创建了一个类,它实现了LifecycleObserver接口,并且我写了几个模拟生命周期的方法,并在每个方法上加上了日志.

public class MyObserver implements LifecycleObserver {

    private static final String TAG = "MyObserver";

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

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

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

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

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

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

3. 注册观察Activity生命周期

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //添加一个生命周期观察者    getLifecycle()是FragmentActivity中的方法
        MyObserver observer = new MyObserver();
        getLifecycle().addObserver(observer);
    }
}

观察运行打印日志

2019-03-12 22:14:26.672 15790-15790/? W/MyObserver: onCreate: 
2019-03-12 22:14:26.676 15790-15790/? W/MyObserver: onStart: 
2019-03-12 22:14:26.679 15790-15790/? W/MyObserver: onResume: 
2019-03-12 22:15:13.054 15790-15790/? W/MyObserver: onPause: 
2019-03-12 22:15:13.234 15790-15790/? W/MyObserver: onStop: 
2019-03-12 22:15:13.241 15790-15790/? W/MyObserver: onDestroy: 

为此我们可以用这个来观察acitvity生命周期,并及时处理回收处理等操作,保证内存泄漏等问题。

二、Lifecycle原理解析

1.activity是如何分发生命周期的?

我们从使用入手,点击getLifecycle()

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

我们看到mLifecycleRegistry是ComponentActivity的一个成员变量,用来管理向其注册生命周期观察者

public class ComponentActivity extends Activity
        implements LifecycleOwner, KeyEventDispatcher.Component {
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }   
}

LifecycleRegistry是Lifecycle的一个实现,而Lifecycle是一个抽象类,里面有3个方法(添加观察者和移除观察者,获取当前的状态)

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();

    @SuppressWarnings("WeakerAccess")
    public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE,
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY
    }


    @SuppressWarnings("WeakerAccess")
    public enum State {

        DESTROYED,


        INITIALIZED,


        CREATED,


        STARTED,


        RESUMED;


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

2.竟然有了观察管理者LifecycleRegistry,它又是如何分发生命周期的呢?

点击进入ComponentActivity的onCreate()方法,里面有ReportFragment,看名字是不是很熟悉,难道这个就是用来上报Activity生命周期的?

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

没错,其实ReportFragment就是在Activity中添加一个空白Fragment,有Fragment的生命周期,当然我们就知道了Activity的生命周期,接着通知相关的观察者即可.

public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        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();
        }
}

其实这个injectIfNeededIn()看起来像是注入的方法干的就是将Fragment添加到Activity中,

来看看这个ReportFragment的生命周期方法都干了些啥,

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
    dispatch(Lifecycle.Event.ON_CREATE);
}

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

private void dispatchCreate(ActivityInitializationListener listener) {
    if (listener != null) {
        listener.onCreate();
    }
}

通过调用dispatchCreate(mProcessListener)方法,感觉从命名上看分发当前的生命周期事件.
dispatch(Lifecycle.Event.ON_START); 也像是在分发事件.

我们跟着这个mProcessListener来看看是在哪里设置的

/**
 * Class that provides lifecycle for the whole application process.
 */
public class ProcessLifecycleOwner implements LifecycleOwner {
    
    //注意,我是一个单例
    private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();

    static void init(Context context) {
        sInstance.attach(context);
    }

    void attach(Context context) {
        mHandler = new Handler();
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        Application app = (Application) context.getApplicationContext();
        app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                ReportFragment.get(activity).setProcessListener(mInitializationListener);
            }
    
            @Override
            public void onActivityPaused(Activity activity) {
                activityPaused();
            }
    
            @Override
            public void onActivityStopped(Activity activity) {
                activityStopped();
            }
        });
    }
}

//Activity的监听器
ActivityInitializationListener mInitializationListener =
            new ActivityInitializationListener() {
                @Override
                public void onCreate() {
                }

                @Override
                public void onStart() {
                    activityStarted();
                }

                @Override
                public void onResume() {
                    activityResumed();
                }

private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);

//Activity创建的时候,分发Lifecycle.Event.ON_START事件
void activityStarted() {
    mStartedCounter++;
    if (mStartedCounter == 1 && mStopSent) {
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
        mStopSent = false;
    }
}
ReportFragment.java
static ReportFragment get(Activity activity) {
    return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
            REPORT_FRAGMENT_TAG);
}

ProcessLifecycleOwner的attach()中registerActivityLifecycleCallbacks()注册了一个监听器,一旦有Activity创建就给它设置一个Listener.这样就保证了每个ReportFragment都有Listener.

既然是一个全局的单例,并且可以监听整个应用程序的生命周期,那么,肯定一开始就需要初始化. 既然没有让我们在Application里面初始化,那么肯定就是在ContentProvider里面初始化的.

3. ProcessLifecycleOwner 在ContentProvider初始化

public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }
}

1.ProcessLifecycleOwner初始化就不说了,是拿来观察整个应用的生命周期的,其原理就是利用ReportFragment,我们稍后详细到来.
2.LifecycleDispatcher尤其重要.

class LifecycleDispatcher {
    static void init(Context context) {
        ...
        //registerActivityLifecycleCallbacks  注册一个监听器
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }
}
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        //又来注入咯
        ReportFragment.injectIfNeededIn(activity);
    }
    @Override
    public void onActivityStopped(Activity activity) {
    }
    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    }
}

初始化的时候,就注册了一个监听器,每个创建的时候都给它注入一个ReportFragment.
那为什么在Activity onCreate还要再注入一个ReportFragment,可能2次注入,确保万无一失,但不管注册几次,内部实现是只会成功注入一次的,所以多调用一次,无所谓

4.事件分发

前面讲的有点啰嗦,接下来我们来看下是如何一步一步分发生命周期事件的

ReportFragment.java
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
    dispatch(Lifecycle.Event.ON_CREATE);
}

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

    if (activity instanceof LifecycleOwner) {
        //获取Activity中的LifecycleRegistry
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}

private void moveToState(State next) {
    ......
    sync();
    ......
}

private void sync() {
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    
    //循环 遍历所有观察者
    while (...) {
        ....
        //分发事件
        forwardPass(lifecycleOwner);
    }
}

注意看分发生命周期会根据状态,小于当前状态的都会一并分发

private void forwardPass(LifecycleOwner lifecycleOwner) {
    Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
            mObserverMap.iteratorWithAdditions();
    while (ascendingIterator.hasNext() && !mNewEventOccurred) {
        Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
        ObserverWithState observer = entry.getValue();
        while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
                && mObserverMap.contains(entry.getKey()))) {
            pushParentState(observer.mState);
            //分发事件
            observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
            popParentState();
        }
    }
}

相关文章

网友评论

      本文标题:Lifecycle_原理解析

      本文链接:https://www.haomeiwen.com/subject/fmagartx.html