Android Jetpack Components of Lifecycle study notes

Android Jetpack Components of Lifecycle study notes

Android Jetpack Components of LiveData study notes

Android Jetpack Components of ViewModel study notes

 

It is said that a large copy of the world's articles. But I am not worried, and I never plagiarize the opinions of others.

Some people say that 90% of the content on blogs and GibHub are duplicates. I agree with this sentence, but I don't think it is a bad thing. No one should have his own dialectical understanding of the same thing, otherwise it will really become a big copy of the world's articles.

In order to clarify my own understanding, to make notes for future review, and to make it easier for latecomers to avoid detours, I still muster the courage to write a follow-up article. Although there are so many great gods who have published similar excellent articles.

Talking a lot of nonsense, today I am going to talk about the Lifecycle component.

Component address: https://developer.android.google.cn/topic/libraries/architecture/lifecycle

You can also refer to the series of articles by this big guy: https://www.jianshu.com/p/b1208012b268

Interjection nonsense:

To access the official Android website https://developer.android.com, you need to go over the wall, otherwise you will not be able to access;

Visit the Android Chinese website https://developer.android.google.cn without going over the wall.

It seems that the content is the same as the .com website, and the official .google.cn website will be updated regularly.

Lifecycle environment configuration:

1. If the sdk is less than 26, the dependency package needs to be imported android.arch.lifecycle

2. If it is an androidx environment, the dependency package also needs to be imported, please refer to  https://developer.android.google.cn/jetpack/androidx/releases/lifecycle#declaring_dependencies

3. Except for the above, no import is required. Starting from SDK 26, the Lifecycle dependency package is built in the system.

 

Lifecycle official original definition:

Lifecycle-aware components perform actions in response to a change in the lifecycle status of another component, such as activities and fragments. These components help you produce better-organized, and often lighter-weight code, that is easier to maintain.

I have read the official explanation and read many excellent blogs, saying that Lifecycle is a component that can perceive the life cycle of Activity and Fragment.

Here is a demo to illustrate the problem. It is an analogy of the registration of a tool class to the anti-registration. The traditional way of writing is as follows:

public class TestBus {
    private Activity mActivity;

    public void registerBusEvent(Activity activity) {
        this.mActivity = activity;
        // TODO: 2019/8/11 if
    }

    public void unRegister(Activity activity) {
        // TODO: 2019/8/11 if
    }
}
public class LifecycleActivity extends AppCompatActivity {
    private TestBus mTestBus;

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

        mTestBus = new TestBus();
        mTestBus.registerBusEvent(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTestBus != null) {
            mTestBus.unRegister(this);
        }
    }
}

Summarizing the official explanation and the opinions of the great gods, the above code has the following shortcomings:

1. In case the mTestBus object forgets to de-register in the onDestroy() method of Activity, will it be a tragedy?

2. If there are more similar functional classes, all of which are de-registered in the onDestroy() method of Activity, the amount of invalid code increases, is it also a tragedy?

3. Activity This is a proxy class for life cycle callbacks between the system process and the application process, and too much business code should not be written.

 

In order to solve the above problems, there is a Lifecycle component, which can perceive the life cycle of Activity and Fragment, and similar anti-registration code can be completely processed in its own business. Let's go to the complete Demo first, let's talk about the details:

public class TestBus implements LifecycleObserver {
    private Activity mActivity;

    public void registerBusEvent(Activity activity) {
        this.mActivity = activity;
        // TODO: 2019/8/11 if
    }

    private void unRegister(Activity activity) {
        // TODO: 2019/8/11 if
    }

    // 需要监控 Activity onDestroy
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        unRegister(mActivity);
    }
}
public class LifecycleActivity extends AppCompatActivity {
    private TestBus mTestBus;

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

        mTestBus = new TestBus();
        mTestBus.registerBusEvent(this);

        // 注册 lifecycle 观察者
        getLifecycle().addObserver(mTestBus);
    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        if (mTestBus != null) {
//            mTestBus.unRegister(this);
//        }
//    }
}

 

After reading the above code, you will find that the obvious change in Activity is that the onDestroy() method is annotated. So the question is, how does TestBus know if the anti-registration method of TestBus is not called in the onDestroy() method of Activity? Does Lifecycle use Activity as an event source to be observed, and then let TestBus as an observer to observe the life cycle of Activity? Let's take a little bit of the source code.

 

First look at the code in the onCreate() method of Activity in the above Demo, it feels like a registered observer:

getLifecycle().addObserver(mTestBus);

You will find that `getLifecycle()` finally returns the `mLifecycleRegistry` object in `SupportActivity`.

Further analysis of `LifecycleRegistry` will find that `Lifecycle` is an abstract class, which provides several abstract methods and two enumeration classes. At the same time, `LifecycleRegistry` inherits the abstract class of `Lifecycle`.

In the constructor of `LifecycleRegistry`, it is found that an instance of the `LifecycleOwner` interface needs to be passed in. It happens that `SupportActivity` implements this interface.

At the same time, `SupportActivity` implements the abstract method `getLifecycle()` of the interface, and the returned type must be of the `Lifecycle` type. It just so happens that the `getLifecycle()` method of `SupportActivity` returns a `LifecycleRegistry` type.

We continue to analyze the code `getLifecycle().addObserver(mTestBus);` Like adding an observer object to the `mLifecycleRegistry` object, the required parameter type must be `LifecycleObserver`. Coincidentally, the `TestBus` in the Demo implements the interface `LifecycleObserver`.

After a short analysis, we understand that:

1. `SupportActivity` has a built-in `LifecycleRegistry` object. When constructing the `LifecycleRegistry` object, it passes in its own memory reference.

2. `LifecycleRegistry` is the management class of the life cycle state of the Activity event source, which is created when `Activity` is initialized.

3. `getLifecycle().addObserver(mTestBus);` This line of code is to register the observer object, and the observer will be notified when the life cycle of the event source changes.

At this point, we understand most of the principles of `Lifecycle`, and what is left is the function of several annotations in `TestBus` in the above example, and how the life cycle of the event source is triggered to the annotation method of `TestBus`.

Search for the `Lifecycle.State` enumeration class, and find that it is used in the `LifecycleDispatcher.makeState()` method. Continue to trace the specific enumeration of `Lifecycle.State` in `LifecycleDispatcher`, and you will find that it is used in the `LifecycleDispatcher.onActivitySaveInstanceState()` method, and it is also used extensively in the inner class of `LifecycleDispatcher.DestructionReportFragment`. From this speculation, it can be concluded that when the life cycle of `Activity` and `Fragment` changes, the event state will be triggered actively, and eventually they will be called to the `LifecycleRegistry.makeToState()` method to notify all observers of the object in a loop The corresponding method.

After understanding the above event notification process, there is another step I don’t know. Whenever an event is triggered, how does LifecycleRegistry know which method of the observer needs to be called back?

Or how can the onDestroy() method of TestBus in the above example be called back by LifecycleRegistry?

We observe the method of registering observers:

LifecycleRegistry.java
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
    // 注意看 ObserverWithState 的构造函数
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    
    // ...
}
ObserverWithState.java
ObserverWithState(LifecycleObserver observer, State initialState) {
    // 注意看 Lifecycling.getCallback() 方法
    mLifecycleObserver = Lifecycling.getCallback(observer);
    mState = initialState;
}
Lifecycling.java
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
    if (object instanceof FullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }
     if (object instanceof GenericLifecycleObserver) {
        return (GenericLifecycleObserver) object;
    }
     final Class<?> klass = object.getClass();
    
    // 注意看这个方法
    int type = getObserverConstructorType(klass);
    // ...
}
Lifecycling.java
private static int getObserverConstructorType(Class<?> klass) {
    if (sCallbackCache.containsKey(klass)) {
        return sCallbackCache.get(klass);
    }
    // 注意看这个方法
    int type = resolveObserverCallbackType(klass);
    sCallbackCache.put(klass, type);
    return type;
}
Lifecycling.java
private static int resolveObserverCallbackType(Class<?> klass) {
    // anonymous class bug:35073837
    
    // 此行代码
    boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
        
}
ClassesInfoCache.java
boolean hasLifecycleMethods(Class klass) {
    if (mHasLifecycleMethods.containsKey(klass)) {
        return mHasLifecycleMethods.get(klass);
    }

    Method[] methods = getDeclaredMethods(klass);
    for (Method method : methods) {
        OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
        if (annotation != null) {
            // Optimization for reflection, we know that this method is called
            // when there is no generated adapter. But there are methods with @OnLifecycleEvent
            // so we know that will use ReflectiveGenericLifecycleObserver,
            // so we createInfo in advance.
            // CreateInfo always initialize mHasLifecycleMethods for a class, so we don't do it
            // here.
            createInfo(klass, methods);
            return true;
        }
    }
    mHasLifecycleMethods.put(klass, false);
    return false;
}

The code is traced here, I don't want to say anything more. Annotation, reflection!

So far, the source code analysis is very clear.

Demo Site: https://github.com/mengzhinan/Lifecycle_LiveData_ViewModel_demo

 

 

 

 

Guess you like

Origin blog.csdn.net/fesdgasdgasdg/article/details/99212772