Q1: Lifecycle will be used and the problems to be solved

LifeCycle externally provides the ability to perceive the LifeCycle, internally using the “observer pattern”. The working principle is implemented in the framework layer by injecting HolderFragment as the subject object. Its role is twofold:

  • Aware of life cycle State and Event –> State State transitions.
  • Distribute events to observers.

Initialize the

public class LifeCycleDemoFragment extends Fragment {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(new LifecycleEventObserver() {
            @Override
            public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
                if (event == Lifecycle.Event.ON_CREATE) {
                    Log.d("hlwang"."Lifecycle onCreate....");
                } else if (event == Lifecycle.Event.ON_RESUME) {
                    Log.d("hlwang"."Life cycle onResume....");
                } else if (event == Lifecycle.Event.ON_START) {
                    Log.d("hlwang"."Lifecycle onStart....");
                } else if (event == Lifecycle.Event.ON_PAUSE) {
                    Log.d("hlwang"."Lifecycle onPause....");
                } else if (event == Lifecycle.Event.ON_STOP) {
                    Log.d("hlwang"."Lifecycle onStop....");
                } else if (event == Lifecycle.Event.ON_DESTROY) {
                    Log.d("hlwang"."Life cycle onDestory...."); }}}); }}Copy the code

role

LifeCycle provides the ability for external components to sense the Android Activity/Fragemnt LifeCycle. The loosely-coupled design provides one-to-many dependencies between objects so that all observers of the lifecycle object can be notified and updated when the state of the object changes.

Attached: Official Google docs

Application scenarios

  • Determine whether the application is in the foreground or background
if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {// The page is in the foreground

} else {// The page is in the background

}
Copy the code
  • Do some operations to free resources based on the declared cycle.
    • Handler in onDestory removes resources that are no longer used, avoiding a MemoryLeak
    • AutoDisponse + RxLifeCycle
    • Jetpack Lifecycle + LiveData is a cascading observer

Q2: Is there anything extra to note about adding observers in different lifecycle methods?

A2: Observer objects can be added in any lifecycle via getLifecycle().addobServer. But the number of callbacks is different.

If an observer is registered in onPause, the observer’s onStateChanged executes multiple times!!

That is:

  • 1.onPauseThe lifecycle Event of theSTARTEDOf the State.
  • 2, whengetLifecycle().addObserver, initial State =INITIALIZED.
  • 3, fromINITIALIZED –> CREATED –> STARTED, onStateChanged will receive multiple callbacks from onCreate to onStop.
01-17 22:26:12.353 D/ hlWANG (12536): onPause --> Lifecycle onCreate.... 01-17 22:26:12.359 D/ HLWANG (12536): onPause --> Lifecycle onStart.... 01-17 22:26:12.930D/HLWANG (12536): onPause --> Lifecycle onStop.... 01-17 22:26:12.972 D/ HLWANG (12536): onPause --> Lifecycle onDestory....Copy the code

Q3: Implementation principle and scenario extension

3.1, the Activity

ComponentActivity in the Activity inheritance tree should be in SupportActivity in the ROM source code. During the onCreate life cycle,

Path:androidx.activity.Com ponentActivitypublic class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner.ViewModelStoreOwner.SavedStateRegistryOwner.OnBackPressedDispatcherOwner {

    / * * * {@inheritDoc}
     *
     * If your ComponentActivity is annotated with {@link ContentView}, this will
     * call {@link #setContentView(int)} for you.
     */
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateRegistryController.performRestore(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
        if(mContentLayoutId ! =0) { setContentView(mContentLayoutId); }}}Copy the code

3.2, fragments

In the Fragment implementation class, in the lifecycle method, you’ll see an implementation like this:

3.3. Other scenarios, such as Application

If Lifecycle is also wanted by a user who has a low client version and the cost of migrating to AndroidX and other higher versions, then Lifecycle can be used:

Path: androidx. Lifecycle. ProcessLifecycleOwnerpublic class ProcessLifecycleOwner implements LifecycleOwner {
    ActivityInitializationListener mInitializationListener =
            new ActivityInitializationListener() {
                @Override
                public void onCreate(a) {}@Override
                public void onStart(a) {
                    activityStarted();
                }

                @Override
                public void onResume(a) { activityResumed(); }};void attach(Context context) {
        mHandler = new Handler();
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        Application app = (Application) context.getApplicationContext();
        app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                ReportFragment.get(activity).setProcessListener(mInitializationListener);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                activityPaused();
            }

            @Override
            public void onActivityStopped(Activity activity) { activityStopped(); }}); }@NonNull
    @Override
    public Lifecycle getLifecycle(a) {
        return mRegistry;
    }

    void activityStarted(a) {
        mStartedCounter++;
        if (mStartedCounter == 1 && mStopSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
            mStopSent = false; }}void activityResumed(a) {
        mResumedCounter++;
        if (mResumedCounter == 1) {
            if (mPauseSent) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
                mPauseSent = false;
            } else{ mHandler.removeCallbacks(mDelayedPauseRunnable); }}}// ...
}
Copy the code