Preface:

Forgive me for the clickbait 😑😑

Lifecycle series:

Lifecycle — (1) The basics

Lifecycle – (2) Source code analysis Event & State

Lifecycle – (3) Source code analysis of the register & send

Lifecycle – (4) Source code analysis of the response

Pending:

Lifecycle – (5) Integrate Lifecycle in several ways with the source code differences

It’s been a long time since I wrote this article, but I recently decided to write about another basic piece of Android: the official Android architecture component series. Lifecycle is going to be written down, so this series will be about Lifecycle.

While I can’t guarantee that everyone will fully digest this, I have no problem (forgive me for covering my face again) with a few mediocre interviewers.


This series is for three types of readers:

  1. Lifecycle has not been used at all, but for those of you who have heard it for the first time and want to go from the shallow to the deep, I will have examples from real life to make it easier for you to grasp
  2. Readers who know a little about the whole basic process and can give a general overview, but have no in-depth understanding
  3. I have also written about Lifecycle myself and have written what I consider to be a reader of the Whole Lifecycle source Code Parsing

Some people will say that why would you say that a third generation will read this article (of course there will be writers who will know the full details that Lifecycle will not write and that can be ignored)

For example I will ask a few simple Lifecycle interview questions:

  1. Lifecycle We know that many articles have said that when you write XXXLifecycleObserver, it will automatically generate XXXLifeObserver_LifecycleAdapter. But I didn’t introduce annotationProcessor “android. Arch. Lifecycle: the compiler: 1.1.1”, does not automatically generate the supporting documents, this time is how correction notice.

  2. Why Lifecycle State and Event are defined this way and why are there only so many values for State?

  3. Is FastSafeIterableMap, the queue that manages our observers in LifecycleRegistry, the Map structure we normally use? If it’s not what it is, talk a little bit about this data structure.

  4. For example, when updating the status in the sync() method, the following section of the code should be familiar to the authors of the source code:

private void sync() {
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        return;
    }
    while(! isSynced()) { mNewEventOccurred =false; / *'Many authors write this introduction by saying simply compare the State of the observer at the head of the queue to the current State, and if it's small, do the backwardPass method, and if it's large, do the forwardPass method. '* /if(mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { backwardPass(lifecycleOwner); / *'excuse me, are now that perform backwardPass operations, why not here added directly return code, and perform over after backwardPass to judge forwardPass??? '* /'return; // Why not add return? '
        }
        
        Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
        if(! mNewEventOccurred && newest ! = null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred =false; } / *'Why is backwardPass used to compare the head of the queue and forwardPass used to compare the tail of the queue? '
    
     'Why is a forward iterator used when executing forwardPass and a reverse iterator used when executing backwardPass? '* /Copy the code

5. Etc etc other problems (too much to write o(╥﹏╥)o)





Body:

1.

Lifecycle — > Lifecycle — > LifecycleObserver

For details, we can look at the brain map.


2. Basics:

About the foundation, you can directly view the basic knowledge on the official website:

Use lifecycle aware components to handle the lifecycle

2.1 Integration Mode 1:

I’ll briefly list the code:

** Activity (host) ** :

//'Implementing LifecycleOwner interface is like putting a note on the door that says,' I have an agent who can help me with my house, get an agent. '
public class MainActivity extends Activity implements LifecycleOwner {
    
    private LifecycleRegistry registry = new LifecycleRegistry(this);
    
    
    //'Look at the number at the door, tell you who the agent is, and go straight to him.'
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        returnregistry; } / /Buyers' 1 '
    private LifeObserver observer1 = new LifeObserver();
    //Buyers' 2 '
    private LifeObserver observer2 = new LifeObserver();
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //'Got the real estate agent, and then buyer 1 registered with the real estate agent.'
        getLifecycle().addObserver(observer1);
        //"Got the real estate agent, and then buyer 2 registered with the real estate agent."getLifecycle().addObserver(observer2); } / /'The landlord has changed his mind'
    @Override
    protected void onResume() {
        super.onResume();
        
        //'The agent immediately informed each buyer of the landlord's new idea.'registry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); } / /'The landlord has changed his mind'
    @Override
    protected void onPause() {
        super.onResume();
        
        //'The agent immediately informed each buyer of the landlord's new idea.'registry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE); } / /'The landlord has changed his mind'
    @Override
    protected void onStop() {
        super.onStop();
        
        //'The agent immediately informed each buyer of the landlord's new idea.'registry.handleLifecycleEvent(Lifecycle.Event.ON_STOP); } / /'Home Buyer category'
    class LifeObserver implements LifecycleObserver{

        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
        public void AAAA(LifecycleOwner owner, Lifecycle.Event event){
            //'The buyer receives a notice from the agent...... '
            Log.v(TAG,"AAAA : "+ event.name()); }}}Copy the code

Yes, this is the fundamental way Lifecycle will be used. You know how to use it all at once.

2.1 Integration Mode 2:

My Activity is different from your code. It doesn’t have a lot of miscellaneous code.

public class Main2Activity extends AppCompatActivity {

    //'buyer'
    private LifeObserver observer = new LifeObserver();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //'Buyers register with agents'getLifecycle().addObserver(observer); }}Copy the code

Isn’t it a lot less? There’s no need to duplicate each lifecycle and send events, and there’s no need to implement the LifecycleOwner interface, but as we said, if you buy a house and you go through this process, you can’t lose anything. It just helps us code some things in advance.

We look at the code for AppCompatActivity:

public class AppCompatActivity extends FragmentActivity implements AppCompatCallback, SupportParentable, DelegateProvider {

}


public class FragmentActivity extends SupportActivity implements ViewModelStoreOwner, OnRequestPermissionsResultCallback, RequestPermissionsRequestCodeValidator {

}


//'We have AppcompatActivity which is equivalent to inheriting SupportActivity'
//'Sure enough, LifecycleOwner interface is implemented.'
public class SupportActivity extends Activity implements LifecycleOwner, Component {
    
    //'Sure enough, I instantiated this real estate agent.'
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    
    //'Implements this method, too, and returns the realtor object'
    public Lifecycle getLifecycle() {
        returnthis.mLifecycleRegistry; } / /'This will be explained to you in detail, read RxPermission source code, should know at a glance'protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); }... . . } / /'Unified Agent distribution of Landlord Information'
public class ReportFragment extends Fragment {
    
    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        
        //'The agent immediately informed each buyer of the landlord's new idea.'
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        dispatchResume(mProcessListener);
        
        //'The agent immediately informed each buyer of the landlord's new idea.'
        dispatch(Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onPause() {
        super.onPause();
        
        //'The agent immediately informed each buyer of the landlord's new idea.'
        dispatch(Lifecycle.Event.ON_PAUSE);
    }

    @Override
    public void onStop() {
        super.onStop();
        
        //'The agent immediately informed each buyer of the landlord's new idea.'
        dispatch(Lifecycle.Event.ON_STOP);
    }
    
    
    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) {
                //'handleLifecycleEvent(Event); To send notifications'((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); }}}}Copy the code

So the code you’re writing is essentially the same code that we just wrote.

2.1 Integration Mode 3:

Of course, if your support package is older, there may be a default for anything like AppcompatActivity that doesn’t automatically integrate Lifecycle code, and then we don’t want to write that much integration (copying every Lifecycle event and calling the send event code). What if you want to implement a usage solution similar to integration Approach 2??

implementation 'android. Arch. Lifecycle: extensions: 1.1.1'
Copy the code

We just need to implement the extension pack above.

public class MainActivity extends Activity implements LifecycleOwner {
    
    private LifecycleRegistry registry = new LifecycleRegistry(this);
    
    @Override
    public Lifecycle getLifecycle() {
        returnregistry; } / /Buyers' 1 '
    private LifeObserver observer1 = new LifeObserver();
    //Buyers' 2 '
    private LifeObserver observer2 = new LifeObserver();
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //'Got the real estate agent, and then buyer 1 registered with the real estate agent.'
        getLifecycle().addObserver(observer1);
        //"Got the real estate agent, and then buyer 2 registered with the real estate agent."getLifecycle().addObserver(observer2); }}Copy the code

We’ll talk about the exact principles later, so there’s no hurry.

Code quantity of integration mode 1 > code quantity of integration mode 3 > code quantity of integration mode 2

So Lifecycle can be used in different situations.


3. Usage Scenarios:

3.1 Ordinary Activities, Fragments and other life cycle monitoring

This basically covers something like 90 percent of the requirements.

For example we happen to be using MVP mode and I am now going to introduce Lifecycle so that when V layer is destroyed we can have P layer unbundled (P layer unbundled with M layer, P layer unbundled with M layer, P layer destroyed, M layer destroyed, etc.)

3.2 Listen on the entire App

A relatively common requirement, for example, I now APP running, I click the Home button, the APP back to the background, at this time I back to the background, a certain code, the APP back from the background, and to execute other code, how to write this listener.

Usually, most people write it like this:

public class DemoApplication extends Application {

    private int appCount;
    private boolean isRunInBackground;
    
    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                appCount++;
                if(isRunInBackground) {// The operation that the application needs to do from the background back to the foreground isRunInBackground =false;
                    //xxxxxxxxxxxxxx
                }
            }
            
            @Override
            public void onActivityStopped(Activity activity) {
                appCount--;
                if(appCount == 0) {isRunInBackground =true; //xxxxxxxxxxxxxx } } ...... . . }); }}Copy the code

If all activities are in the Stop state, they are in the background. If all activities are in the Start state, and our Boolean variable is true, they are in the foreground.

There is nothing wrong with Lifecycle, of course we will use Lifecycle:

First you need to introduce the expansion pack implementation “android. Arch. Lifecycle: extensions: 1.1.1”


ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifeObserver());

class LifeObserver extends LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onForeground} @onlifecycleEvent (Lifecycle.event.ON_STOP) public void (Lifecycle.eventonBackground() {// Enter the background}}Copy the code

Actually this ProcessLifecycleOwner used source, also with our registerActivityLifecycleCallbacks (new ActivityLifecycleCallbacks ()) principle is the same, He just helped us encapsulate a lot of code. The specific piece of source code analysis, I will elaborate later.

3.3 With LiveData, message bus

Evolution of Android message Bus: Replace RxBus and EventBus with LiveDataBus

3.4 other


conclusion

In this paper, we can learn the basic way of use, through the landlord-intermediate-homebuyer, can better understand.