當前位置:網站首頁>組件化之路 - Lifecycle一知半解

組件化之路 - Lifecycle一知半解

2022-01-27 03:30:49 Modu_Liu

减法、减法、做减法,終於在2021年的最後一天把這篇 Lifecycle 基本完善了,話說做技術真是學無止境啊 ~

Android Architecture Components 架構組件

關於Lifecycle的學習,以及Lifecycle近幾年的一個發展情况,都可以結合 官方文檔 與 三方blog進行補課 ~

基本認知

Google於2017年在JetPack下推出了Lifecycle組件,主要用於動態感知Activity、Fragment組件的生命周期,隨著Lifecycle組件的不斷更新,現在已經可以感知Application和Service的生命周期
在這裏插入圖片描述

關於Lifecycle如何動態感知生命周期組件?主要還是因其內部采用了觀察者模式,Activity、Fragment這樣的基礎組件作為被觀察者後,一般我們只需定義觀察者即可~

  • LifecycleOwner 被觀察者 (被監聽者,提供了生命周期)
  • LifecycleObserver 觀察者(監聽者,只要生命周期改變,我們都可以實時感知)

Look Here:其實Lifecycle的觀察者有倆種實現方式

具體使用哪種觀察者自己看就行,性能上也沒啥區別

  • DefaultLifecycleObserver 感知生命周期與綁定組件的生命周期相對應
  • LifecycleObserver 結合 @OnLifecycleEvent注解實現動態監聽,靈活性較高

像Activity、Fragment作為被觀察者,如何綁定觀察者?…嗯,看完下面的 “小小源碼” 你就知道用addObserver 了,具體如下

   getLifecycle().addObserver(觀察者);

在早期1.0版本時,使用Lifecycle組件需要引入相關的依賴implementation "android.arch.lifecycle:extensions:1.0.0-alpha4",直到2018年以後,也就是 support library26.1.0Lifecycle才處於一個相對穩定的版本

之所以稱之為穩定版本,主要是Lifecycle被Google集成到了Activity和Fragment的基類,這點在Lifecycle的1.1.0版本中已經提到了~
在這裏插入圖片描述
接著我們可以打開項目跟著Activity或Fragment看看基類的接口實現

Activity - AppCompatActivity - FragmentActivity - ComponentActivity 我們可以看到在ComponentActivity已經實現了LifecycleOwner接口 > <
在這裏插入圖片描述
Fragment 可以直接看到已經實現了LifecycleOwner 接口
在這裏插入圖片描述

小小源碼

既然學習Lifecycle,那麼我們來看一下Lifecycle中都有什麼 ~

源碼

僅是部分錶面源碼,並入深入,等有需求或時間的話,在去細讀內部源碼

package androidx.lifecycle;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.RestrictTo;

import java.util.concurrent.atomic.AtomicReference;

public abstract class Lifecycle {
    

    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    @NonNull
    AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();

    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);
    
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    /** * Returns the current state of the Lifecycle. * * @return The current state of the Lifecycle. */
    @MainThread
    @NonNull
    public abstract State getCurrentState();

    @SuppressWarnings("WeakerAccess")
    public enum Event {
    
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY
    }

    @SuppressWarnings("WeakerAccess")
    public enum State {
    
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;

        public boolean isAtLeast(@NonNull State state) {
    
            return compareTo(state) >= 0;
        }
    }
}
方法分析

如果你熟悉觀察者模式的話,有的方法很好理解

  • addObserver 添加觀察者
  • removeObserver 删除觀察者
  • getCurrentState 獲取當前狀態
  • Event枚舉 生命周期與組件周期相對應
 public enum Event {
    
        /** * Constant for onCreate event of the {@link LifecycleOwner}. */
        ON_CREATE,
        /** * Constant for onStart event of the {@link LifecycleOwner}. */
        ON_START,
        /** * Constant for onResume event of the {@link LifecycleOwner}. */
        ON_RESUME,
        /** * Constant for onPause event of the {@link LifecycleOwner}. */
        ON_PAUSE,
        /** * Constant for onStop event of the {@link LifecycleOwner}. */
        ON_STOP,
        /** * Constant for onDestroy event of the {@link LifecycleOwner}. */
        ON_DESTROY,
        /** * An {@link Event Event} constant that can be used to match all events. * Look here : 這裏稍微注意一下,只要組件的生命周期改變,就會調用該回調 */
        ON_ANY
    }
  • State枚舉 State代錶階段性的生命周期
    public enum State {
    
        /** * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch * any more events. For instance, for an {@link android.app.Activity}, this state is reached * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call. * 順序值為0 */
        DESTROYED,

        /** * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is * the state when it is constructed but has not received * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet. * 順序值為1 */
        INITIALIZED,

        /** * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; * <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call. * </ul> * 順序值為2 */
        CREATED,

        /** * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onStart() onStart} call; * <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call. * </ul> * 順序值為3 */
        STARTED,

        /** * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached after {@link android.app.Activity#onResume() onResume} is called. * 順序值為4 */
        RESUMED;

        /** * Compares if this State is greater or equal to the given {@code state}. * * @param state State to compare with * @return true if this State is greater or equal to the given {@code state} */
        public boolean isAtLeast(@NonNull State state) {
    
            return compareTo(state) >= 0;
        }
    }
為何Event與State不對應?

我們可以看到Event有7個狀態,而State為何只有5個狀態?它們是如何對應的?其實這個以前我看別人 blog 圖畫的挺好的,直接就借鑒說明一下吧~

官方解釋

其實官方的圖,解釋的也蠻清楚的,錶明了State處於不同階段時,Event都執行了哪些生命周期(這裏要注意,Create、Start、Resume 一般都有對應的生命周期 如 Destroy、Stop、Pause
請添加圖片描述
我看了一下那篇 blog 講的,其實就像我上面說的一樣,當你把生命周期組成小組對應關系時,就能很快理解為何State和Event不同了,當然源碼中可能說的是用數字去判斷狀態這樣的邏輯 > <
請添加圖片描述

基本使用

Lifecycle文檔提示了,要配置
在這裏插入圖片描述
build.gradle

allprojects {
    
    repositories {
    
        jcenter()
        google()
    }
}

官網依賴,示例

    dependencies {
    
        def lifecycle_version = "2.4.0"
        def arch_version = "2.1.0"

        // ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
        // LiveData
        implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
        // Lifecycles only (without ViewModel or LiveData)
        implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

        // Saved state module for ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

        // Annotation processor
        annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
        // alternately - if using Java8, use the following instead of lifecycle-compiler
        implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

        // optional - helpers for implementing LifecycleOwner in a Service
        implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"

        // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
        implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

        // optional - ReactiveStreams support for LiveData
        implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"

        // optional - Test helpers for LiveData
        testImplementation "androidx.arch.core:core-testing:$arch_version"
    }

bulid.gradle 個人示例:因為Lifecycle用到了JDK1.8的東西,所以在build.gradle(Module)加入以下配置

android {
    
    ...
    compileOptions {
    
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    
	...
    implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0"
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation "androidx.lifecycle:lifecycle-service:2.2.0"
}

其實在使用Lifecycle中,我們很少自己寫 LifecycleOwner 被觀察者, 主要是因為基礎組件基本都實現了LifecycleOwner 接口

定義 ActivityOwner (被觀察者)

首先說明一下,Owner被觀察者一般都不需要自己寫 ,之所以這裏會寫,主要是為了讓大家了解一下 被觀察者都做了什麼?

package com.example.lifecycle;

import android.app.Activity;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;

/** * @author MrLiu * @date 2021/12/31 * desc 自定義被觀察者 */
public class BasicActivity extends Activity implements LifecycleOwner {
    

    private LifecycleRegistry lifecycleRegistry;

	//實現LifecycleOwner 接口後需要重寫的方法
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
    
        return lifecycleRegistry;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic);
        //這行比較關鍵:注册Lifecycle的組件
        lifecycleRegistry = new LifecycleRegistry(this);
        //設置組件周期狀態
        lifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
        //綁定觀察者,這裏的觀察者下面有說明
        getLifecycle().addObserver(new MainLifecycleObserver());
    }

    @Override
    protected void onStart() {
    
        super.onStart();
        lifecycleRegistry.setCurrentState(Lifecycle.State.STARTED);
    }

    @Override
    protected void onResume() {
    
        super.onResume();
        lifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
    }
    
	//這裏都沒有設置狀態,主要是State是階段性的一個狀態,具體可以看上方提到的
    @Override
    protected void onPause() {
    
        super.onPause();
    }
    
	//這裏都沒有設置狀態,主要是State是階段性的一個狀態,具體可以看上方提到的
    @Override
    protected void onStop() {
    
        super.onStop();
    }

    @Override
    protected void onDestroy() {
    
        super.onDestroy();
        lifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
    }

}
定義 LifecycleObserver (觀察者)

沒事兒做,寫個 Observe 玩一玩 ,下面用的是@OnLifecycleEvent注解方式觀察者,主要是一個簡單的生命周期感知學習,用到的是 @OnLifecycleEvent(Lifecycle.Event.XXXXX)注解 ~

MainLifecycleObserver

package com.example.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/** * @author MrLiu * @date 2021/12/20 * desc LifecycleObserver 觀察者 */
class MainLifecycleObserver implements LifecycleObserver {
    

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void any() {
    
        System.out.println("Main: any");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void create() {
    
        System.out.println("Main: create");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void start() {
    
        System.out.println("Main: start");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void resume() {
    
        System.out.println("Main: resume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void pause() {
    
        System.out.println("Main: pause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void stop() {
    
        System.out.println("Main: stop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void destroy() {
    
        System.out.println("Main: destroy");
    }

}
Lifecycle 組件集成效果

組件啟動
在這裏插入圖片描述
組件啟動 - 組件銷毀
在這裏插入圖片描述

使用方式

關於Lifecycle常見的使用場景,一般有三種!

  • LifecycleObserver
  • DefaultLifecycleObserver
  • LifecycleObserver + 組件封裝

這裏寫個Activity,作為下面觀察的被觀察者

package com.example.lifecycle;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //綁定觀察者:LifecycleObserver 觀察者
        getLifecycle().addObserver(new MainLifecycleObserver());
        //綁定觀察者:DefaultLifecycleObserver 觀察者
        getLifecycle().addObserver(new DefaultLifecycleObserver());
        //綁定觀察者:LifecycleObserver觀察者 + 組件封裝
        getLifecycle().addObserver(new VideoPlayerObserver());
    }
}
LifecycleObserver

MainLifecycleObserver

package com.example.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/** * @author MrLiu * @date 2021/12/20 * desc LifecycleObserver 觀察者 */
class MainLifecycleObserver implements LifecycleObserver {
    

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void any() {
    
        System.out.println("Main: any");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void create() {
    
        System.out.println("Main: create");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void start() {
    
        System.out.println("Main: start");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void resume() {
    
        System.out.println("Main: resume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void pause() {
    
        System.out.println("Main: pause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void stop() {
    
        System.out.println("Main: stop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void destroy() {
    
        System.out.println("Main: destroy");
    }

}

MainLifecycleObserver - 測試效果

組件啟動
在這裏插入圖片描述
組件啟動 - 組件銷毀
在這裏插入圖片描述

DefaultLifecycleObserver

使用實現DefaultLifecycleObserver接口的觀察者,需要依賴implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0",要注意其內部的生命周期都是固定的,我們直接重寫接口的方法即可,擴展性稍微有限 ~

DefaultLifecycleObserver

package com.example.lifecycle;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

/** * @author MrLiu * @date 2021/10/27 * desc DefaultLifecycleObserver 觀察者 */
public class DefaultLifecycleObserver implements androidx.lifecycle.DefaultLifecycleObserver {
    
    private static String TAG = "lifecycle";

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
    
        Log.e(TAG, "create");
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
    
        Log.e(TAG, "start");
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
    
        Log.e(TAG, "resume");
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
    
        Log.e(TAG, "pause");
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
    
        Log.e(TAG, "stop");
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
    
        Log.e(TAG, "destroy");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void any() {
    
        Log.e(TAG, "any");
    }

}

DefaultLifecycleObserver - 測試效果

組件啟動 (上面我特意寫了LifecycleObserver的注解方式,然後你可以發現在DefaultLifecycleObserver 是無效的哈~
在這裏插入圖片描述
組件啟動 - 組件銷毀
在這裏插入圖片描述

LifecycleObserver + 組件封裝

在真實開發中,我們經常有些業務在Activity、Fragment生命周期改變時做出相應的改變,網上常見的示例就是 Video 在特定的周期內播放、暫停、回收 ~

package com.example.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/** * @author MrLiu * @date 2021/12/31 * desc 組件+Lifecycle封裝 */
public class VideoPlayerObserver implements LifecycleObserver {
    

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void playVideo() {
    
        System.out.println("開始播放VideoView");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void pauseVideo() {
    
        System.out.println("組件在走onPause周期,先停止播放Video吧");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void finish() {
    
        System.out.println("取消VideoView的播放,防止內存泄露");
    }
}

VideoPlayerObserver - 測試效果
在這裏插入圖片描述

使用場景

在不同的組件場景中,使用Lifecycle的方式都有小小區別,繼續吧

Activity 場景

關於Activity場景的使用,其實完全可以使用上面寫到的使用方式,這裏的話,我直接將上方部分copy下來一個節點,免得有些朋友跳的看blog,而導致錯過這部分內容

MainLifecycleObserver - 觀察者

package com.example.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/** * @author MrLiu * @date 2021/12/20 * desc LifecycleObserver 觀察者 */
class MainLifecycleObserver implements LifecycleObserver {
    

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    public void any() {
    
        System.out.println("Main: any");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void create() {
    
        System.out.println("Main: create");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void start() {
    
        System.out.println("Main: start");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void resume() {
    
        System.out.println("Main: resume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void pause() {
    
        System.out.println("Main: pause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void stop() {
    
        System.out.println("Main: stop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void destroy() {
    
        System.out.println("Main: destroy");
    }

}

MainActivity - 被觀察者

package com.example.lifecycle;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //綁定觀察者:LifecycleObserver 觀察者
        getLifecycle().addObserver(new MainLifecycleObserver());
    }
}

MainLifecycleObserver - 測試效果

組件啟動
在這裏插入圖片描述
組件啟動 - 組件銷毀
在這裏插入圖片描述

Service 場景

看了挺多blog,很少有提到LifecycleService這個類,自行可以追代碼看到LifecycleService是屬於Service的一個子類,且內部實現了LifecycleOwner接口,內部已經自行封裝監聽了Service的生命周期,我們可以直接使用這個類

依賴:implementation "androidx.lifecycle:lifecycle-service:2.2.0"

look here:Service的Lifecycle並非集成到Service父類(壓根沒父類,它就是基類),而是使用了Service派發的LifecycleService子類
在這裏插入圖片描述
VideoPlayerObserver - 觀察者

package com.example.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/** * @author MrLiu * @date 2021/12/31 * desc 組件+Lifecycle封裝 */
public class VideoPlayerObserver implements LifecycleObserver {
    

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void playVideo() {
    
        System.out.println("開始播放VideoView");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void finish() {
    
        System.out.println("終止VideoView的播放,防止內存泄露");
    }
}

TestService - 被觀察者

package com.example.lifecycle;

import androidx.lifecycle.LifecycleService;

/** * @author MrLiu * @date 2021/12/31 * desc 通過LifecycleService實現動態感知Service生命周期 */
public class TestService extends LifecycleService {
    
    @Override
    public void onCreate() {
    
        super.onCreate();
        getLifecycle().addObserver(new VideoPlayerObserver());
    }
}

MainActivity

我這裏是在Activity動態啟動,終止服務

package com.example.lifecycle;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    

    private Intent serviceIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		//啟動服務
        serviceIntent = new Intent(this, TestService.class);
        startService(serviceIntent);
    }

    @Override
    protected void onDestroy() {
    
        super.onDestroy();
        //終止服務
        stopService(serviceIntent);
    }
}

測試效果
在這裏插入圖片描述

Application 場景

關於Application對於Lifecycle的集成稍有不同,因為監聽Application生命周期的是ProcessLifecycleOwner類,見名猜其意:進程生命周期擁有者

依賴:implementation "androidx.lifecycle:lifecycle-process:2.2.0"(有的依賴包含此項,並非必須添加,但是添加沒壞處 - -)

一個操作系統中有很多軟件,每個軟件中有很多進程,每個進程中有很多線程,但是常規每個app啟動後,我們都將其看做是一個進程,進程關閉後app也就被關閉了
在這裏插入圖片描述
TestAppLifecycleObserver - 觀察者

package com.example.lifecycle;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/** * @author MrLiu * @date 2021/12/20 * desc 觀察者 */
class TestAppLifecycleObserver implements LifecycleObserver {
    

// @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
// public void any() {
    
// System.out.println("TestApplication: any");
// }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void create() {
    
        System.out.println("TestApplication: create");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void start() {
    
        System.out.println("TestApplication: start");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void resume() {
    
        System.out.println("TestApplication: resume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void pause() {
    
        System.out.println("TestApplication: pause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void stop() {
    
        System.out.println("TestApplication: stop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void destroy() {
    
        System.out.println("TestApplication: destroy");
    }

}

TestApplication - 被觀察者,稍有特殊

package com.example.lifecycle;

import android.app.Application;

import androidx.lifecycle.ProcessLifecycleOwner;

/** * @author MrLiu * @date 2021/12/31 * desc Application 被觀察者 */
public class TestApplication extends Application {
    

    @Override
    public void onCreate() {
    
        super.onCreate();
        //綁定觀察者:以下的綁定方式,稍有特殊
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new TestAppLifecycleObserver());
    }
}

記得將我們的Application配置到AndroidMainfests

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lifecycle">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
       android:name=".TestApplication"
        android:theme="@style/Theme.Lifecycle">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

測試效果
在這裏插入圖片描述
嗯... 這就完了??? 有沒有發現沒有監聽到應用的onDestroy???

通過查看ProcessLifecycleOwner類,可以發現壓根內部沒有封裝onDestroy生命周期,Application因為是將整個進程作為生命周期的提供類,所有有些特殊,例如下面這些特點

  • Lifecycle.Event.ON_CREATE 只會被調用一次,而 Lifecycle.Event.ON_DESTROY 永遠不會被調用。
  • ProcessLifecycleOwner 是針對整個應用程序的監聽,與 Activity 的數量無關
  • Lifecycle.Event.ON_PAUSELifecycle.Event.ON_STOP 的調用會有一定的延後,因為系統需要為“屏幕旋轉,由於配置發生變化而導致的 Activity 重新創建” 的情况預留一些時間
    在這裏插入圖片描述

版權聲明
本文為[Modu_Liu]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/01/202201270330490154.html

隨機推薦