preface

At Google I/O in 2018, Google announced Android Jetpack, which it described as the next generation of Android components designed to help developers speed up app development. Specifically, Jetpack is a collection of Android software components, including basic components, architectural components, behavioral components, and interface components. The Android Architecture Components refer to the “Architecture Components” here.

Android Architecture Components is a Google recommended application Architecture for building apps. It contains a number of architecture-related Components. Lifecycle is one of those libraries that will be introduced in this article. Lifecycle is also tied to both the LiveData and ViewModel libraries, and understanding them is essential.

See the following two images from the official website for details of the relationships between the components and their respective positions in Jetpack.

The role of the Lifecycle

Lifecycle is a Lifecycle aware component, that is, we can be notified when changes occur in the Lifecycle of an Activity or Fragment. We tend to perform specific methods within the various lifecycle methods of an Activity, such as registering and unbundling broadcasts, registering and unbundling Eventbus, and so on:

public class TestActivity extends AppCompatActivity {

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

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() { EventBus.getDefault().unregister(this); super.onDestroy(); }}Copy the code

If we put much of this lifecycle dependent logic code directly into the Activity lifecycle methods, the Activity would become difficult to maintain. With Lifecycle we can avoid this problem. Because essentially all we need is for us to be notified when the Activity or Fragment life cycle changes so that we can execute the corresponding method in the corresponding life cycle.

Basic use of Lifecycle

2.0. Import Lifecycle dependencies

Lifecycle is included in the Support Library 26.1.0 and later, and if our project relies on a support library version 26.1.0 or later, there is no need to import Lifecycle, which is 28.0.0 in this example:

    implementation 'com. Android. Support: appcompat - v7:28.0.0'Copy the code

If the support library version is less than 26.1.0 Lifecycle library will need to be imported separately:

    implementation "Android. Arch. Lifecycle: the runtime: 1.1.1"Copy the code

Of course, if the project has been migrated to AndroidX, it can be imported using the following method:

    implementation "Androidx. Lifecycle: lifecycle - runtime: 2.0.0." "Copy the code

Again, I recommend that you try to move your project to AndroidX as soon as possible, as many updates will be released in AndroidX first, moving away from traditional support packages. For example Lifecycle has been upgraded to 2.x on AndroidX and 1.x on the support library.

Given that the support libraries are generally above 26.1.0 and that most users have not migrated to AndroidX, for this article we will use the Lifecycle library that is included by default in the support library 28.0.0. We added the following dependencies to the build.gradle file in our project’s app directory:

    implementation 'com. Android. Support: appcompat - v7:28.0.0'Copy the code

On the premise that the Support Library version is 26.1.0 or above, here we are divided into two cases. One is that we can create an Activity that inherits from AppCompatActivity(which is similar to Fragment in the case of an Activity), and the other is that we can create an Activity that inherits from normal activities rather than AppCompatActivity.

Lifecycle will be implemented in the observer mode and knowing this as a whole will make it easier to understand how Lifecycle will work: 1. Build a Lifecycle object (returned by the getLifecycle() method of an object that implements the LifecycleOwner interface) that will be observed and have Lifecycle awareness 2. Build a LifecycleObserver object that listens for the specified Lifecycle object 3. By adding addObserver(…) to Lifecycle object Method to bind Lifecycle object to LifecycleObserver object

2.1, inherit from AppCompatActivity

First, we create a myObserver. Java class that implements the LifecycleObserver interface (the LifecycleObserver interface is an empty interface intended primarily for annotation processors) as follows:

public class MyObserver implements LifecycleObserver {

    private static final String TAG = "MyObserver"; // Use the annotation @onlifecycleEvent to indicate that the method needs to listen for the specified LifecycleEvent @onlifecycleEvent (Lifecycle.event.on_resume) public voidconnectListener() {/ /... Log.d(TAG,"connectListener: -------- onResume" );
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void disconnectListener() {/ /... Log.d(TAG,"disconnectListener: ------- onPause"); }}Copy the code

As you can see, we made the method lifecycle aware by using the @onlifecycleEvent annotation on the method. The arguments in parentheses indicate what lifecycle events you want to listen for. Lifecycle tracks the Lifecycle State of the associated component primarily through the two enumerated classes Event and State. For the specific conversion relationship between Event and State, please refer to the following figure:

Next, let’s make our Activity inherit from AppCompatActivity and then onCreate(…) Lifecycle and LifecycleObserver are bound with getLifecycle().addobServer (new MyObserver()).

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); GetLifecycle ().addobServer (new MyObserver()); }}Copy the code

We can then run the program, switch to Home or press the back key, and see that the methods defined in MyObserver() are correctly printed in the console as the life cycle changes.

Doesn’t it seem so easy.

But it’s effortless because someone else is carrying the load for you. In support Library 26.1.0 and later, the parent class SupportActivity of AppCompatActivity already implements the LifecycleOwner interface by default. Lifecycle() returns a Lifecycle object directly through its getLifecycle() method. We can then pass the object’s addObserver(…) The Lifecycle method binds Lifecycle to the specified LifecycleObserver.

2.2. Inherit from normal Activities

First, we still need to create a MyObserver object as above.

This time we will create an Activity that inherits from a normal Activity that will not be able to getLifecycle directly using the getLifecycle() method. Can we emulate the implementation of AppCompatActivity and create Lifecycle objects ourselves? B: Sure. At this point, we need to implement the LifecycleOwner interface ourselves and use the LifecycleRegistry markState(…) for the specific lifecycle. Method to proactively distribute events. Look at the modified mainactivity.java code below:

public class MainActivity extends Activity implements LifecycleOwner {

    private LifecycleRegistry mLifecycleRegistry;

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

        mLifecycleRegistry = new LifecycleRegistry(this);
        getLifecycle().addObserver(new MyObserver());
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLifecycleRegistry.markState(Lifecycle.State.RESUMED);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mLifecycleRegistry.markState(Lifecycle.State.STARTED);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        returnmLifecycleRegistry; }}Copy the code

MainActivity implements the LifecycleOwner interface (the object that implements that interface, which is the holder of Lifecycle) and returns a LifecycleRegistry object in its getLifecycle() method, LifecycleRegistry is a subclass of Lifecycle. Other uses are exactly the same.

Lifecycle also provides a way to query the Lifecycle state of the current component to make it more flexible:

lifecycle.getCurrentState().isAtLeast(STARTED)Copy the code

conclusion

  1. Classes that implement the LifecycleObserver interface can work seamlessly with classes that implement the LifecycleOwner interface because LifecycleOwner can provide a Lifecycle object, LifecycleObserver needs to listen on this Lifecycle object.
  2. LifecycleOwner is the holder of Lifecycle that is abstracted from a specific class such as an Activity or Fragment.
  3. The LifecycleRegistry class is used to register and unregister LifecycleObservers that need to observe the current component lifecycle

Pay attention to

Starting with the 1.0.0-rC1 package Lifecycle will be marked as CREATED and ON_STOP immediately after the onSaveInstanceState() method of the Activity is called. Instead of waiting for the onStop() method call to finish. This does not match the order in which activities are called in their lifecycle on API Level 26 or lower, so be careful. If you have specific requirements, you can refer to relevant documents.

In the next article, Lifecycle’s source code will be dissected.

For more latest news, please follow my official account: