当前位置:网站首页>How does activity implement lifecycleowner?

How does activity implement lifecycleowner?

2022-06-23 14:14:00 User 9239674

We all know Activity Can be used as LifecycleOwner by LiveData Provide conditions for the use of , that Activity How to achieve LifecycleOwner What about ?

Activity Although it did LifecycleOwner Interface , But it doesn't implement the relevant processing , But by adding a Fragment To represent Lifecycle Distribution of . Such passage Fragment agent Activity Behavior design is also common in other libraries , Relatively more uninhibited and elegant .

SupportActivity

Activity By inheritance SupportActivity Realization LifecycleOwner Interface . Pay attention to AndroidX in SupportActivity Renamed as ComponentActivity

public class SupportActivity extends Activity implements LifecycleOwner {

    ...

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    ...

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveInstanceState(outState);
    }

    ...

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

SupportActivity The statement mLifecycleRegistry object , But it's not directly used for lifecycle distribution , But be ReportFragment adopt activity.getLifecycle() Get use .

ReportFragment

SupportActivity stay onCreate Add... To yourself ReportFragment

@RestrictTo(LIBRARY_GROUP)
public class SupportActivity extends Activity implements LifecycleOwner {
  // ...

  @Override
  @SuppressWarnings("RestrictedApi")
  protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ReportFragment.injectIfNeededIn(this);
  }

  // ...
}

Low version Activity compatible Lifecycle

SupportActivity It's accompanied by Lifecycle That's what happened ,android.arch.lifecycle:extensions For the early period has not yet inherited SupportActivity Of Activity There is also support , adopt LifecycleDispatcher Realization ReportFragment The injection of :

class LifecycleDispatcher {

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

    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
        private final FragmentCallback mFragmentCallback;

        DispatcherActivityCallback() {
            mFragmentCallback = new FragmentCallback();
        }

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            if (activity instanceof FragmentActivity) {
                ((FragmentActivity) activity).getSupportFragmentManager()
                        .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
            }
            ReportFragment.injectIfNeededIn(activity);
        }

    }
}

I was wondering why ReportFragment The implementation of does not write SupportActivity In the middle , See here, finally understand the meaning of its existence .

LifecycleDispatcher There is no need to Application Call in , He passed ContentProvider Implement initialization

public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }    
}

stay android.arch.lifecycle:extensionsaar Of AndroidManifest Register in :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.arch.lifecycle.extensions" >

    <uses-sdk android:minSdkVersion="14" />

    <application>
        <provider
            android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
            android:authorities="${applicationId}.lifecycle-trojan"
            android:exported="false"
            android:multiprocess="true" />
    </application>

</manifest>

${applicationId} Place holder , avoid authroities Conflict .

It can be seen that we have achieved the utmost in the matter of non invasion , This noninvasive initialization method is worth learning and using .

Two kinds of Fragment

Through the analysis above , We know Activity It's through ReportFragment Agent LifecycleOwner The implementation of the . So in Activity Added in LifecycleOwner And Activity Of Fragment Is the life cycle consistent ? The answer is No

Android There are two kinds of Fragment There are two kinds of :

  • ADK Self contained android.app.Fragment
  • Support In bag android.support.v4.app.Fragment(AndroidX It also falls into this category )

Because the former has been @Deprecated, So the latter is now widely used , That is to say Support perhaps AndroidX Of Fragment. And for the sake of low version compatibility ,ReportFragment It's the former .

Activity For both Fragment The reality of lifecycle callbacks is not the same , With onResume and onStart For example ,Activity The actual callback is shown in the following table :

In the table above () The numbers in represent the order of execution , So you will find ,sdk fragment Of onStart Later than support fragment, and onResume But earlier

Activity Of LifecycleOwner Although it is based on Fragment Realized , But the same Activity Of LifecycleOwner And Fragment The lifecycle callback of is actually not consistent .

This is very important in our development , Don't let Fragment and LifecycleOwner The processing in the life cycle of the process produces temporal dependencies .

summary

* Through source code analysis Activity about LifecycleOwner After the realization of , We come to the following conclusion

  • Activity Do not call directly HandleLifecycleEvent Distribution of life cycle , But through ReportFragment Realization
  • ReportFragment The injection and the whole process are noninvasive , It is worth learning from
  • The same Activity, Its LifecycleOwner And Fragment The lifecycle callback of is actually not consistent , Special attention required

Android Advanced development system notes 、 The latest interview review notes PDF, my GitHub

At the end of the article

Your favorite collection is my greatest encouragement ! Welcome to follow me , Share Android dried food , communication Android technology . What's your opinion on the article , Or any technical problems , Welcome to leave a message and discuss in the comment area !

原网站

版权声明
本文为[User 9239674]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201071644200370.html