Jetpack 之 LifeCycle

1,985 阅读2分钟

  解耦是软件架构设计中的永恒话题,在Android开发中,解耦很大程度上表现为系统组件的生命周期与自定义组件之间的解耦,自定义组件在使用过程中要依赖系统组件生命周期实现,有时候我们不得不在系统组件的生命周期事件中增加回调方法。我们希望对自定义组件的管理不依赖系统组件的生命周期,同时在页面生命周期发生改变时,可以通知自定义组件。这种模式在组件化架构设计中尤为重要。

  为此,Google提供了LifeCycle作为解决方案。LifeCycle可以帮助开发者创建感知组件生命周期的组件,组件可以在其内部管理自己的生命周期,从而减低模块之间的耦合度,并降低内存泄漏的风险。LifeCycle可以广泛应用于 Activity、Fragment、Service、Application的生命周期监控。

1.LifeCycle 原理

  LifeCycle采用的是观察者模式,Jetpack为我们提供了两个类:LifecycleOwner(被观察者)、LifecycleObserver(观察者),实现对系统组件生命周期监控。

  通过查看ComponentActivity源码我们可以看到,新版本的SDK中Activity已经默认实现了LifecycleOwner接口,LifecycleOwner接口中只有一个getLifecycle()方法LifecycleOwner就是通过该方法实现观察者模式的。

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner {

     ...

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
   
    public ComponentActivity() {
        Lifecycle lifecycle = getLifecycle();
        //noinspection ConstantConditions
        if (lifecycle == null) {
            throw new IllegalStateException("getLifecycle() returned null in ComponentActivity's "
                    + "constructor. Please make sure you are lazily constructing your Lifecycle "
                    + "in the first call to getLifecycle() rather than relying on field "
                    + "initialization.");
        }
        if (Build.VERSION.SDK_INT >= 19) {
            getLifecycle().addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                    if (event == Lifecycle.Event.ON_STOP) {
                        Window window = getWindow();
                        final View decor = window != null ? window.peekDecorView() : null;
                        if (decor != null) {
                            decor.cancelPendingInputEvents();
                        }
                    }
                }
            });
        }
        getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source,
                    @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_DESTROY) {
                    if (!isChangingConfigurations()) {
                        getViewModelStore().clear();
                    }
                }
            }
        });

        if (19 <= SDK_INT && SDK_INT <= 23) {
            getLifecycle().addObserver(new ImmLeaksCleaner(this));
        }
    }

    ...

    @CallSuper
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        Lifecycle lifecycle = getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
        }
        super.onSaveInstanceState(outState);
        mSavedStateRegistryController.performSave(outState);
    }

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

    ...

 
}

2.使用LifeCycle 解耦Activity和组件

  (1)首先我们创建一个用于感知Activity生命周期的监听类 PerceptionLifeListener,PerceptionLifeListener实现LifecycleObserver 接口。使用@OnLifecycleEvent注解,定义需要监听的生命周期;具体代码如下:

public class PerceptionLifeListener implements LifecycleObserver {
    private static final String TAG = "PerceptionLifeListener";

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void onCreat(){
        Log.d(TAG,"onCreat");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onStart(){
        Log.d(TAG,"onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void onResume(){
        Log.d(TAG,"onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void onPause(){
        Log.d(TAG,"onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void onStop(){
        Log.d(TAG,"onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void onDestroy(){
        Log.d(TAG,"onDistory");
    }
}

  (2)我们在需要被监听的Activity中注册该监听,具体代码如下:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册生命感知监听
        PerceptionLifeListener perceptionLifeListener = new PerceptionLifeListener();
        getLifecycle().addObserver(perceptionLifeListener);
    }
}

至此,LifeCycle已经解决了组件对Activity生命周期的依赖问题,我们看下运行结果:

image.png