LifeCycle introduction

LifeCycle is a component that can sense changes in the LifeCycle of the host. Common hosts include activities/fragments, Services, and applications. LifeCycle holds information about the state of the host’s LifeCycle and notifies observers listening to the host when changes occur during the host’s LifeCycle.

LifeCycle appears primarily to address the coupling between the LifeCycle of system components and common components.

  • System components include activities/fragments, Services, and applications.
  • A generic component is a component that encapsulates code in terms of function or function.

In what cases is the life cycle of a system component coupled with the life cycle of a common component?

Here’s an example:

There is a business requirement for video playback in 58 Tribes business. We need to initialize the video playback component in the Activity, stop the video playback in onPause(), and reclaim the video playback component and some resources in onDestroy(). This is cumbersome and leads to high coupling between pages and components.

For this kind of problem LifeCycle can be solved completely. It not only reduces the coupling degree between modules, but also reduces the possibility of memory leaks.

2. the use of LifeCycle

Jetpack provides us with two interfaces:

Observed: LifecycleOwner

Observer: LifecycleObserver

The monitored system component needs to implement the LifecycleOwner interface, and the observer needs to implement the LifecycleObserver interface.

LifeCycle decouples pages from components

(1) Decouple the Activity

Step 1: Add dependencies

Implementation 'androidx. Appcompat: appcompat: 1.2.0'Copy the code

LifecycleOwner interface is implemented by default for ComponentActivity in AndroidX. If the project is not migrated to AndroidX and still uses the Support library, the new SDK also implements the LifecycleOwner interface through SupportActivity.

In the LifecycleOwner interface, there is only one getLifecycle method.

Step 2: Implement the observer

If you want to listen to the lifecycle of an Activity, all you need to do is to customize the component and implement the LifecycleObserver interface, which has no interface methods and does not require any concrete implementation.

Take, for example, the video I just played:

  1. Create a MyVideoPlayListener class that implements the LifecycleObserver interface and does all the video-playing logic in this class. For methods within components that need to be notified when the Activity Lifecycle changes, use the @onlifecycleEvent (Lifecycle.event.on_xxx) annotation so that when the Activity Lifecycle changes, The marked method is automatically called.
public class MyVideoPlayListener implements LifecycleObserver { private static String TAG = "MyVideoPlayListener"; @OnLifecycleEvent(Lifecycle.Event.ON\_CREATE) private void initVideo(){ Log.d(TAG,"initVideo"); } @OnLifecycleEvent(Lifecycle.Event.ON\_RESUME) private void startPlay(){ Log.d(TAG,"startPlay"); } @OnLifecycleEvent(Lifecycle.Event.ON\_PAUSE) private void pausePlay(){ Log.d(TAG,"pausePlay"); }}Copy the code

2. Reference MyVideoPlayListener in MainActivity.

public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity\_main); MyVideoPlayListener listener = new MyVideoPlayListener(); getLifecycle().addObserver(listener); }}Copy the code

##### (2) Decoupled Fragment

In newer versions of the SDK, Fragments also implement the LifecycleOwner interface by default, so the examples above are also appropriate for fragments.

#### (2) Application Scenario 2: Use LifecycleService to decouple services from components

(1) LifecycleService

In addition to activities/Fragments, another very important component with a life cycle in Android is Service. LifecycleService is used to listen and decouple Service components.

public class LifecycleService extends Service implements LifecycleOwner { private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this); . @Override @NonNull public Lifecycle getLifecycle() { return mDispatcher.getLifecycle(); }}Copy the code
(2) Specific use methods

Step 1: Add related dependencies

Implementation "androidx lifecycle: lifecycle - service: 2.2.0." "Copy the code

Step 2: Create the MyServiceObserver class that implements the LifecycleObserver interface. Use the @onlifecycleEvent tag to tag methods that you want to call synchronously when the Server life cycle changes.

public class MyServiceObserver implements LifecycleObserver { private static String TAG = "MyServiceObserver"; @OnLifecycleEvent(Lifecycle.Event.ON\_CREATE) private void initVideo(){ Log.d(TAG,"initVideo"); } @OnLifecycleEvent(Lifecycle.Event.ON\_DESTROY) private void pausePlay(){ Log.d(TAG,"stopPlay"); }}Copy the code

Step 3: Create a MyService class that inherits LifecycleService. Because LifecycleService is a direct subclass of Service, it is used the same as a normal Service.

public class MyService extends LifecycleService { private MyServiceObserver myServiceObserver; public MyService(){ myServiceObserver = new MyServiceObserver(); getLifecycle().addObserver(myServiceObserver); }}Copy the code

##### (3) Usage Scenario 3: Use ProcessLifecycleOwner to listen for the application lifecycle

In addition to activities, fragments, and Services, there are applications that have a life cycle. The ProcessLifecycleOwner is used to listen for the entire application lifecycle.

Specific use method:

Step 1: Add dependencies

Implementation "androidx. Lifecycle: lifecycle - process: 2.2.0." "Copy the code

Step 2: Define an ApplicationObserver that implements the LifecycleObserver interface.

public class ApplicationObserver implements LifecycleObserver { private String TAG = this.getClass().getName(); /\*\* * will only be called once in the entire Lifecycle of the application \*/ @onlifecycleEvent (Lifecycle.event.on \_CREATE) public void onCreate() { Log.d(TAG,"Lifecycle.Event.ON\_CREATE"); } @OnLifecycleEvent(Lifecycle.Event.ON\_START) public void onStart() { Log.d(TAG,"Lifecycle.Event.ON\_START"); } @OnLifecycleEvent(Lifecycle.Event.ON\_RESUME) public void onResume() { Log.d(TAG,"Lifecycle.Event.ON\_RESUME"); } @OnLifecycleEvent(Lifecycle.Event.ON\_PAUSE) public void onPause() { Log.d(TAG,"Lifecycle.Event.ON\_PAUSE"); } @OnLifecycleEvent(Lifecycle.Event.ON\_STOP) public void onStop() { Log.d(TAG,"Lifecycle.Event.ON\_STOP"); } /\*\* \* will never be called, OnLifecycleEvent(Lifecycle.event.ON\_DESTROY) public void onDestroy() { Log.d(TAG,"Lifecycle.Event.ON\_DESTROY"); }}Copy the code

Step 3: Associate ApplicationObserver with the Application.

public class App extends Application { @Override public void onCreate() { super.onCreate(); ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationObserver()); }}Copy the code

Matters needing attention:

  1. ProcessLifecycleOwner is a listener for the entire application, regardless of the number of activities.
  2. ON_CREATE will only be called once and Lifecycle.Event.ON_DESTROY will never be called.
  3. Lifecycle.Event.ON_PAUSE and Lifecycle.Event.ON_STOP calls will be delayed because the system will need to allow some time for “screen rotation and Activity re-creation due to configuration changes”.

3. Lifecycle can be written in two other ways

Lifecycle can be implemented in three ways:

  1. LifecycleObserver with annotations
  2. The FullLifecyclerObserver has all the lifecycle events of the host
  3. LifecycleEventObserver Host Lifecycle events encapsulated as Lifecycle.Event

In the previous section, we used the first approach: LifecycleObserver with annotations.

This is easier to use, but note that it is better to add the annotation processor lifecycle- Compiler, or else use reflection to call back to the corresponding method at runtime:

AnnotationProcessor "androidx. Lifecycle: lifecycle - compiler: 2.2.0." "Copy the code

With this annotation handler, methods marked with the @onlifecycleEvent tag can no longer be declared private, otherwise the following error will be reported:

method marked with OnLifecycleEvent annotation can not be private  

Copy the code

Here are two other implementations:

FullLifecyclerObserver owns all lifecycle events of the host
// The FullLifecycleObserver interface defines the lifecycle methods, so we just need to implement the FullLifecycleObserver interface and override the corresponding // lifecycle methods. However, the FullLifecycleObserver interface is not currently available to developers. interface FullLifecycleObserver extends LifecycleObserver { void onCreate(LifecycleOwner owner); void onStart(LifecycleOwner owner); void onResume(LifecycleOwner owner); void onPause(LifecycleOwner owner); void onStop(LifecycleOwner owner); void onDestroy(LifecycleOwner owner); }Copy the code
LifecycleEventObserver host Lifecycle events are encapsulated as Lifecycle.Event
// Override onStateChanged by implementing the LifecycleEventObserver interface, Lifecycle.Event Public Class MyVideoPlayObserver implements LifecycleEventObserver {private. Lifecycle static String TAG = "MyVideoPlayObserver"; @Override public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { switch (event){ case ON\_CREATE: Log.d(TAG,"initVideo"); break; case ON\_START: Log.d(TAG,"startPlay"); break; case ON\_RESUME: Log.d(TAG,"resumePlay"); break; default: break; }}}Copy the code

Four,

LifeCycle components exist primarily to help decouple them so that the LifeCycle changes are felt by the components that we define.

Five, the complement

The latest version of Lifecycle_Version is 2.2.0 as of this article’s release. Check out the website for the latest version:

Note: The APIS in Lifecycle -Extensions are deprecated, so when you need to use a tool under Lifecycle, add a dependency:

Dependencies {def lifecycle\_version = "2.2.0" def arch\_version = "2.1.0 "androidx.lifecycle:lifecycle-viewmodel:$lifecycle\_version" // LiveData implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle\_version" // Lifecycles only (without ViewModel or LiveData) implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle\_version" // Saved state module for ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle\_version" // Annotation processor annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle\_version" // alternately - if using Java8, use the following instead of lifecycle-compiler implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle\_version" // optional - helpers for implementing LifecycleOwner in  a Service implementation "androidx.lifecycle:lifecycle-service:$lifecycle\_version" // optional - ProcessLifecycleOwner  provides a lifecycle for the whole application process implementation "androidx.lifecycle:lifecycle-process:$lifecycle\_version" // optional - ReactiveStreams support for LiveData implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle\_version" // optional - Test helpers for LiveData testImplementation "androidx.arch.core:core-testing:$arch\_version" }Copy the code