Decoupling is an eternal topic in software architecture design, in the Android development, decoupling performance largely for the components of the system life cycle and custom components, the decoupling between the custom components in use process need to rely on system component lifecycle implementation, sometimes we have to increase in the components of the system life cycle events callback methods. We want the management of custom components to be independent of the life cycle of system components, and to be able to notify custom components when the page life cycle changes. This pattern is particularly important in componentized architecture design.

To this end, Google offers LifeCycle as a solution. LifeCycle helps developers create components that are aware of the LifeCycle of components and can manage their own LifeCycle internally, thereby reducing coupling between modules and reducing the risk of memory leaks. LifeCycle can be widely used to monitor the LifeCycle of activities, fragments, services, and applications.

1. The LifeCycle theory

LifeCycle uses the observer pattern and Jetpack provides two classes: LifecycleOwner and LifecycleObserver to monitor the LifeCycle of system components.

The LifecycleOwner interface has been implemented by default in the new SDK version. There is only one getLifecycle() method in the LifecycleOwner interface and LifecycleOwner implements the observer pattern through this method.

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; }... }Copy the code

2. Decouple activities and components using LifeCycle

(1) Firstly, we create a PerceptionLifeListener listener class for sensing the Activity life cycle. The PerceptionLifeListener implements the LifecycleObserver interface. Use the @onlifecycleEvent annotation to define the lifecycle to listen on; The specific code is as follows:

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"); }}Copy the code

(2) We register the listener in the Activity that needs to be listened on. The specific code is as follows:

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PerceptionLifeListener = new PerceptionLifeListener(); getLifecycle().addObserver(perceptionLifeListener); }}Copy the code

LifeCycle has now resolved the component’s dependency on the Activity LifeCycle and let’s look at the results: