美文网首页
Lifecycle分析

Lifecycle分析

作者: taijielan | 来源:发表于2020-01-20 14:17 被阅读0次

    首先分析下jetpack框架的入口,ide我使用的是as(3.5)正式版。
    添加依赖库

        implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-rc03'
        implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha02'
    

    先看应用构建完成之后的完整manifest文件,app/build/intermediates/instant_app_manifest/debug/AndroidManifest.xml
    发现有部分我们没有自己写的配置的文件

           <provider
               android:name="androidx.lifecycle.ProcessLifecycleOwnerInitializer"
               android:authorities="com.pinshi.testjetpack.lifecycle-process"
               android:exported="false"
               android:multiprocess="true" />
    

    ProcessLifecycleOwnerInitializer就是Lifecycle组件初始化的地方。这是一个ContentProvider
    会自动调用其中的

       @Override
        public boolean onCreate() {
            LifecycleDispatcher.init(getContext());  //1
            ProcessLifecycleOwner.init(getContext()); //2
            return true;
        }
    ``
    注释1 的部分是将生命周期时间感知,具体的实现是
    

    static void init(Context context) {
    if (sInitialized.getAndSet(true)) {
    return;
    }
    ((Application) context.getApplicationContext())
    .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }

    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    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) {
        }
    }
    
    这个地方的主要作用有2个,一个是通过`registerActivityLifecycleCallbacks()`方法感知Activity或者Fragment 的生命周期变化,另一个是当一些异常情况发生的时候,将会停止所有的关于生命周期的标记。
    注释2的作用是分发生命周期的变化的。
    

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

    直接调用`attach()` 方法。
    

    void attach(Context context) {
    mHandler = new Handler();
    mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); //1
    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();
            }
        });
    }
    
    注释1
    `mRegistry`是`LifecycleRegistry` 继承自`Lifecycle`。主要用于处理生命周期事件。
    在26.0.1的以及更高版本的`support`的`Activity`和`Fragment`中,已经实现了`LifecycleOwer`接口。
    `LifecycleOwer`其实可以理解为被观察者。
    我用`MainActivity`中继承的是`AppCompatActivity`,它继承的是`FragmentActivity`,再上一级继承的是`ComponentActivity`,在其中的`onCreate`方法中,
    

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSavedStateRegistryController.performRestore(savedInstanceState);
    ReportFragment.injectIfNeededIn(this); //1
    if (mContentLayoutId != 0) {
    setContentView(mContentLayoutId);
    }
    }

    1处的`ReportFragment`,绑定它的生命周期
    
    

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

    @Override
    public void onStart() {
        super.onStart(); //1
        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;
    }
    
    
    再看下1处的`dispatchStart ()`方法
    

    private void dispatchStart(ActivityInitializationListener listener) {
    if (listener != null) {
    listener.onStart();
    }
    }

    这里的listener是程序初始化的时候就配置了的 在,`ProcessLifecycleOwner`的`attach()`方法中
    
            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);//1
            }
    
            @Override
            public void onActivityPaused(Activity activity) {
                activityPaused();
            }
    
            @Override
            public void onActivityStopped(Activity activity) {
                activityStopped();
            }
        });
    }
    
    主要的作用是监听`onstart()`和`onResume`方法。设置当前状态的变化和通知当前的被观察者。
    
    
    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);
            }
        }
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:Lifecycle分析

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