Lifecycle awareness is implemented by Android Architecture Components. Lifecycle awareness is implemented by Android Architecture Components. Lifecycle awareness is implemented by Android Architecture Components.

Lifecycle is a component of the Android Architecture Components(hereafter referred to as AAC) that separates the Lifecycle of system Components(activities, fragments, etc.) into the Lifecycle class. Lifecycle allows other classes to act as observers and observe changes in the Lifecycle of a component.

Implement component lifecycle observation practices based on AAC

  • Control implements the LifecycleObserver interface and internally declares lifecycle events via the @onlifecycleEvent annotation
public class LifecycleObserverDemo implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onAny(LifecycleOwner owner, Lifecycle.Event event) {
        System.out.println("onAny:" + event.name());
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate() {
        System.out.println("onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy() {
        System.out.println("onDestroy"); }}Copy the code
  • In LifecycleRegistryOwner, for example, in an Activity that implements the LifecycleRegistryOwner interface. Define the LifecycleRegistry instance and control the listener collection within the LifecycleRegistry instance.
Public class MainActivity extends AppCompatActivity implements LifecycleRegistryOwner {// Define LifecycleRegistry instance private  LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); GetLifecycle ().addobServer (new LifecycleObserverDemo()); } @Override public LifecycleRegistrygetLifecycle() {
        returnlifecycleRegistry; }}Copy the code

With just the above two steps, LifecycleObserverDemo is notified when the Activity page life cycle changes. Similarly, this article uses Activity as an example to introduce the principle of perceiving the Lifecycle.

Lifecycle binding implementation principle

Introduction to Implementation Principles

Pass the page activity lifecycle to the Fragment by registering a UI-free Fragment for the specified activity. LifecycleRegistry is then bound to the Fragment, and when the Fragment’s lifecycle changes, the LifecycleRegistry calls back the corresponding lifecycle callback method of the LifecycleObserver object.

How do I pass the life cycle

The diagram below shows Lifecycle Lifecycle delivery in the Android Architecture Component — Lifecycle Analysis. I think it shows Lifecycle delivery very clearly. Let’s follow this diagram for a step-by-step look at how the life cycle is transmitted.

  • How to register a UI-free ReportFragment on an Activity

    First look at the LifecycleDispatcher initialization process:

    • Use the features of the ContentProvider to inject two lines of code into the application when it is initialized:
    LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); // Listen for the whole application switchCopy the code
    • Where does this ContentProvider come from? The androidmanifest.xml file in APK contains a ContentProvider declaration:
    <provider
        android:name="android.arch.lifecycle.LifecycleRuntimeTrojanProvider"
        android:authorities="${applicationId}.lifecycle-trojan"
        android:exported="false"
        android:multiprocess="true" />
    Copy the code

In this LifecycleRuntimeTrojanProvider (low version of the AAC, this class called ProcessLifecycleOwnerInitializer) initialization method, realized the LifecycleDispatcher corresponding initialization.

Let’s look at the Init method for LifecycleDispatcher again:

static void init(Context context) {
    if (sInitialized.getAndSet(true)) {
        return; } ((Application) context.getApplicationContext()) .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());  }Copy the code

In LifecycleDispatcher# init (Context), it through registerActivityLifecycleCallbacks method, To the current Application to register a DispatcherActivityCallback. But I can’t use ActivityLifecycleCallbacks to listen and Lifecycle and distributing life cycle events. But by a UI fragments in DispatcherActivityCallback# onActivityCreated can see it in Activity# onCreate, Add a ReportFragment to the Activity. LifecycleRegistry is ultimately listened for by ReportFragment.

  • Ui-less fragments connect with LifecycleRegistry

Check the ReportFragment lifecycle callback method:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    dispatchCreate(mProcessListener);
    dispatch(Lifecycle.Event.ON_CREATE);
}

@Override
public void onStart() {
    super.onStart();
    dispatchStart(mProcessListener);
    dispatch(Lifecycle.Event.ON_START);
}

@Override
public void onResume() {
    super.onResume();
    dispatchResume(mProcessListener);
    dispatch(Lifecycle.Event.ON_RESUME);
}

@Override
public void onPause() {
    super.onPause();
    dispatch(Lifecycle.Event.ON_PAUSE);
}

@Override
public void onStop() {
    super.onStop();
    dispatch(Lifecycle.Event.ON_STOP);
}

@Override
public void onDestroy() {
    super.onDestroy();
    dispatch(Lifecycle.Event.ON_DESTROY);
    // just want to be sure that we won't leak reference to an activity mProcessListener = null; }Copy the code

When the Lifecycle method is called back, the dispatch(Lifecycle.Event Event) method is called. Lifecycle.Event Event (dispatch)

private void dispatch(Lifecycle.Event event) {
    Activity activity = getActivity();
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if(lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); }}}Copy the code

LifecycleRegistry is retrieved via the getLifecycle() method of the Activity registered with the ReportFragment, LifecycleRegistry’s handleLifecycleEvent(@nonnull Lifecycle.Event Event) is then called to handle the passed LifecycleEvent.

  • How does lifecycleAdapter connect to LifecycleRegistry

    In LifecycleRegistry, the following map is defined:

    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
    Copy the code

    When we add an observer to the collection in the page Activity, we add the mObserverMap defined above. When the ObserverWithState object constructor is initialized, the GenericLifecycleObserver object is returned via the Lifecycling. GetCallback (Observer) method, which is essentially the _LifecycleAdapter object. Because _LifecycleAdapter implements GenericLifecycleObserver.

    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(); inttype = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            List<Constructor<? extends GeneratedAdapter>> constructors =
                    sClassToAdapters.get(klass);
            if (constructors.size() == 1) {
                GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                        constructors.get(0), object);
                return new SingleGeneratedAdapterObserver(generatedAdapter);
            }
            GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
            for (int i = 0; i < constructors.size(); i++) {
                adapters[i] = createGeneratedAdapter(constructors.get(i), object);
            }
            return new CompositeGeneratedAdaptersObserver(adapters);
        }
        return new ReflectiveGenericLifecycleObserver(object);
    }
    Copy the code

The _LifecycleAdapter class is generated based on annotations, and the _LifecycleAdapter object is generated through reflection

  • _LifecycleAdapter calls back to the lifecycle method to continue passing the lifecycle to the final observer

LifecycleRegistry makes contact with _LifecycleAdapter, and the lifecycle calls the dispatchEvent method with ObserverWithState:

void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = getStateAfter(event);
    mState = min(mState, newState);
    mLifecycleObserver.onStateChanged(owner, event);
    mState = newState;
}
Copy the code

Finally, mLifecycleObserver is called, which is the onStateChanged method of the _LifecycleAdapter we returned earlier. Take a look at the implementation of _LifecycleAdapter:

public class LifecycleObserverDemo_LifecycleAdapter implements GenericLifecycleObserver {
  final LifecycleObserverDemo mReceiver;

  LifecycleObserverDemo_LifecycleAdapter(LifecycleObserverDemo receiver) {
    this.mReceiver = receiver;
  }

  @Override
  public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
    mReceiver.onAny(owner,event);
    if (event == Lifecycle.Event.ON_CREATE) {
      mReceiver.onCreate();
    }
    if (event == Lifecycle.Event.ON_START) {
      mReceiver.onStart();
    }
    if (event == Lifecycle.Event.ON_PAUSE) {
      mReceiver.onPause();
    }
    if (event == Lifecycle.Event.ON_DESTROY) {
      mReceiver.onDestroy();
    }
  }

  public Object getReceiver() {
    returnmReceiver; }}Copy the code

The above class can be found in the build directory. This is the annotation handler that generates the LifecycleObserverDemo_LifecycleAdapter for us, but this is just an adapter that dispatchlife cycle events to the corresponding method of the LifecycleObserverDemo. At this point, LifecycleObserverDemo implements awareness of the page Activity lifecycle.

Introduction to core Classes

  • LifecycleObserver: Interface that marks a class as observable and implements corresponding callback methods based on annotations
  • Lifecycle: Abstract class that has the Android Lifecycle
  • LifecycleRegistry: Lifecycle is inherited and can handle multiple lifecycleobservers
  • LifecycleOwner: interface that holds an Android Lifecycle
  • LifecycleRegistryOwner: interface that inherits LifecycleOwner and returns LifecycleRegistry
  • LifecycleDispatcher: Hook in the Application to observe the activity’s lifecycle and distribute it
  • Initialization LifecycleRuntimeTrojanProvider: LifecycleDispatcher, etc

Lifecycle management framework practices

Demo omits annotation steps and requires observers to implement a ZRLifecycleObserver interface themselves. It’s a little different, but it’s understandable.

The Demo framework is shown below:

It is also relatively simple to use, mainly for the following Settings.

  • The observer implements the ZRLifecycleObserver interface
public class MyView extends View implements ZRLifecycleObserver {

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context,
            @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onCreate() {
        System.out.println("MyView onCreate");
    }

    @Override
    public void onStart() {
        System.out.println("MyView onStart");
    }

    @Override
    public void onResume() {
        System.out.println("MyView onResume");
    }

    @Override
    public void onPause() {
        System.out.println("MyView onPause");
    }

    @Override
    public void onStop() {
        System.out.println("MyView onStop");
    }

    @Override
    public void onDestroy() {
        System.out.println("MyView onDestroy");
    }

    @Override
    public void onRestart() {
        System.out.println("MyView onRestart"); }}Copy the code
  • Initialize ZRLifecycleDispatcher when the application starts
public class MyApplication extends Application {

    @Override
    public void onCreate() { super.onCreate(); ZRLifecycleDispatcher.init(this); }}Copy the code
  • The page being observed implements ZRLifecycleRegistryOwner and adds the observer object to the collection to observe the page lifecycle
public class MainActivity extends Activity implements ZRLifecycleRegistryOwner {

    private ZRLifecycleRegistry lifecycleRegistry = new ZRLifecycleRegistry(this);

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

        MyView myView = findViewById(R.id.view_test);

        getLifecycle().addObserver(myView);

    }

    @Override
    public ZRLifecycleRegistry getLifecycle() {
        returnlifecycleRegistry; }}Copy the code

The project code can be obtained here: CustomAACLifecycleDemo

The end of the

This concludes the rationale for how AAC binds the page life cycle. In the last article how to bind the page life cycle (A) -Glide implementation, introduced the principle of Glide binding life cycle. Two ways to bind the page life cycle, you can compare, I believe that there will be more in-depth understanding of the bound page life cycle.

reference

Android Architecture Component — Lifecycle Analysis