安卓源碼分析(10)Lifecycle實現組件生命周期管理

參考:
https://developer.android.google.cn/topic/libraries/architecture/lifecycle?hl=zh-cn#java
https://developer.android.google.cn/reference/androidx/lifecycle/Lifecycle

文章目錄

    • 1、概述
    • 2、LifeCycle類
    • 3、LifecycleOwner類
    • 4、LifecycleObserver類

1、概述

Android Lifecycle 是一種用于管理 Android 組件(如 Activity 和 Fragment)生命周期的架構組件。Lifecycle 提供了一種在組件生命周期變化時觸發相應操作的方式,以幫助開發者編寫更加健壯和可維護的代碼。

Android 組件的生命周期包括多個階段,如創建(Create)、啟動(Start)、恢復(Resume)、暫停(Pause)、停止(Stop)和銷毀(Destroy)。在每個階段,組件可以執行特定的操作,如初始化界面、加載數據、保存狀態等。例如,經典的Activity組件的生命周期圖:
在這里插入圖片描述

使用 Lifecycle 可以將與組件生命周期相關的操作集中到一個地方,并確保這些操作在正確的時機被調用。說白了,就是將生命周期的管理和業務實現分離,抽象成通用的公共組件,以實現代碼復用和抽象。

在 Android 框架中定義的大多數應用組件都存在生命周期。生命周期由操作系統或進程中運行的框架代碼管理。它們是 Android 工作原理的核心,應用必須遵循它們。如果不這樣做,可能會引發內存泄漏甚至應用崩潰。

Lifecycle 提供了以下主要的元素和功能:

  • LifecycleOwner: 一個實現了 LifecycleOwner 接口的對象,通常是 Activity 或 Fragment。它負責提供生命周期的狀態。
  • Lifecycle : 表示一個組件的生命周期狀態,如 CREATED、STARTED、RESUMED 等。可以通過 Lifecycle 對象來觀察和監聽生命周期狀態的變化。
  • LifecycleObserver: 一個實現了 LifecycleObserver 接口的類,用于觀察和響應生命周期事件。

通過使用 Lifecycle,開發者可以避免常見的生命周期相關問題,如內存泄漏、UI 更新異常、數據不一致等。它提供了一種結構化的方式來管理生命周期,并使代碼更易于理解、測試和維護。

總之,Android Lifecycle 是一種用于管理 Android 組件生命周期的架構組件,它提供了一套機制和工具來觀察、響應和管理組件的狀態變化,使開發者能夠編寫更加可靠和健壯的代碼。

2、LifeCycle類

Lifecycle 是一個類,用于存儲有關組件(如 activity 或 fragment)的生命周期狀態的信息,并允許其他對象觀測此狀態。

Lifecycle 使用兩種主要枚舉跟蹤其關聯組件的生命周期狀態:

事件
從框架和 Lifecycle 類分派的生命周期事件。這些事件映射到 activity 和 fragment 中的回調事件。

狀態
Lifecycle 對象所跟蹤的組件的當前狀態。

跟蹤生命周期的流程如下:
在這里插入圖片描述
熟悉狀態機的同學很容易理解,狀態在發生某些事情時就會躍遷到另一個狀態,上圖的箭頭就描述了某些事件發生時狀態的躍遷。

LifeCycle定義了以下幾種狀態:

    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.*/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.*/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>*/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>*/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.*/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;}}

定義的事件如下:

    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.*/ON_ANY;

LifeCycle除了提供了生命周期的記錄,還提供了觀測的方法,采用了設計模式觀察者模式,

    /*** Adds a LifecycleObserver that will be notified when the LifecycleOwner changes* state.* <p>* The given observer will be brought to the current state of the LifecycleOwner.* For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer* will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.** @param observer The observer to notify.*/@MainThreadpublic abstract void addObserver(@NonNull LifecycleObserver observer);/*** Removes the given observer from the observers list.* <p>* If this method is called while a state change is being dispatched,* <ul>* <li>If the given observer has not yet received that event, it will not receive it.* <li>If the given observer has more than 1 method that observes the currently dispatched* event and at least one of them received the event, all of them will receive the event and* the removal will happen afterwards.* </ul>** @param observer The observer to be removed.*/@MainThreadpublic abstract void removeObserver(@NonNull LifecycleObserver observer);

想要觀測該狀態,需要被Lifecycle添加為觀察者,當然也可以移除解除通知。

同時提供了一個供外部查詢當前狀態的接口:

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

3、LifecycleOwner類

LifecycleOwner只是個簡單的接口類,定義了一個獲取Lifecycle的方法。

public interface LifecycleOwner {/*** Returns the Lifecycle of the provider.** @return The lifecycle of the provider.*/@NonNullLifecycle getLifecycle();
}

想要擁有生命周期管理的組件只要實現該接口即可。

像ComponentActivity就繼承于該接口。

4、LifecycleObserver類

Lifecycle是一個被觀測對象,自然要有觀察者,即關心生命周期變化的人。提供了LifecycleObserver 類用于觀測Lifecycle,學java的都知道,java就喜歡極度抽象,LifecycleObserver 是個空接口類,啥都沒有。

public interface LifecycleObserver {}

觀察者的接口自然是觀測Lifecyle狀態變化,onXXX習慣用于表達XXX事件發生時的回調。

表達事件/狀態變化可以有兩種表達方式,一種是窮舉出所有的事件,一種是通過形參表達,android兩種形式都提供了:

FullLifecycleObserver 窮舉定義了所有事件回調:

interface FullLifecycleObserver extends LifecycleObserver {void onCreate(LifecycleOwner owner);void onStart(LifecycleOwner owner);void onResume(LifecycleOwner owner);void onPause(LifecycleOwner owner);void onStop(LifecycleOwner owner);void onDestroy(LifecycleOwner owner);
}

通過函數形參區分不同事件的接口定義LifecycleEventObserver :

/*** Class that can receive any lifecycle change and dispatch it to the receiver.* <p>* If a class implements both this interface and* {@link androidx.lifecycle.DefaultLifecycleObserver}, then* methods of {@code DefaultLifecycleObserver} will be called first, and then followed by the call* of {@link LifecycleEventObserver#onStateChanged(LifecycleOwner, Lifecycle.Event)}* <p>* If a class implements this interface and in the same time uses {@link OnLifecycleEvent}, then* annotations will be ignored.*/
public interface LifecycleEventObserver extends LifecycleObserver {/*** Called when a state transition event happens.** @param source The source of the event* @param event The event*/void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

注釋里提到,如果一個Observer同時實現了這兩種形式的接口,FullLifecycleObserver的相應接口會先被調用,其次才是onStateChanged這個接口。

同時還定義了一個空實現的DefaultLifecycleObserver,這樣我們可以根據需要,override部分接口。

在最后,我們補全一張類圖:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/35062.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/35062.shtml
英文地址,請注明出處:http://en.pswp.cn/news/35062.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據庫字段命名導致的SQL報錯

1.表設計 create table variables (id bigint not null comment 主鍵,business_key varchar(128) null comment 業務key,key varchar(128) null comment Map中的key,value varchar(255) null comment…

Centos yum命令大全

1.使用YUM查找軟件包 $ yum search python 2.列出所有可安裝的軟件包 $ yum list | grep python 3.列出所有可更新的軟件包 $ yum list updates 4.列出所有已安裝的軟件包 $ yum list installed | grep python

[GIN-debug] [ERROR] listen tcp: address 8080: missing port in address

學習Golang_gin框架的第一天 遇到一下報錯 : [GIN-debug] [ERROR] listen tcp: address 8080: missing port in address 錯誤代碼 : package mainimport "github.com/gin-gonic/gin"func main() {router : gin.Default()router.GET("/index", func…

910數據結構(2014年真題)

算法設計題 問題1 已知一個帶頭結點的單鏈表head&#xff0c;假設結點中的元素為整數&#xff0c;試編寫算法&#xff1a;按遞增次序輸出單鏈表中各個結點的數據元素&#xff0c;并釋放結點所占的存儲空間。要求&#xff1a;(1)用文字給出你的算法思想&#xff1b;(2)不允許使…

nginx禁用3DES和DES弱加密算法

nginx禁用3DES和DES弱加密算法 項目背景 最近護網行動&#xff0c;收到漏洞報告&#xff0c;如下&#xff1a; 漏洞名稱SSL/TLS協議信息泄露漏洞(CVE-2016-2183)【原理掃描】詳細描述TLS是安全傳輸層協議&#xff0c;用于在兩個通信應用程序之間提供保密性和數據完整性。 TLS…

opencv 基礎50-圖像輪廓學習03-Hu矩函數介紹及示例-cv2.HuMoments()

什么是Hu 矩&#xff1f; Hu 矩&#xff08;Hu Moments&#xff09;是由計算機視覺領域的科學家Ming-Kuei Hu于1962年提出的一種圖像特征描述方法。這些矩是用于描述圖像形狀和幾何特征的不變特征&#xff0c;具有平移、旋轉和尺度不變性&#xff0c;適用于圖像識別、匹配和形狀…

C語言鏈表操作

目錄 鏈表基本操作 刪除重復元素 查找倒數第N個節點 查找中間節點 約瑟夫環 循環鏈表 合并有序鏈表 逆置鏈表 逆置鏈表(雙向鏈表) 鏈表基本操作 //linklist.c#include "linklist.h" #include <stdlib.h>struct node *head NULL; struct node *tail…

React 18 state 狀態更新函數

參考文章 把一系列 state 更新加入隊列 設置組件 state 會把一次重新渲染加入隊列。但有時可能會希望在下次渲染加入隊列之前對 state 的值執行多次操作。為此&#xff0c;了解 React 如何批量更新 state 會很有幫助。 React 會對 state 更新進行批處理 在下面的示例中&…

Docker查看、創建、進入容器相關的命令

1.查看、創建、進入容器的指令 用-it指令創建出來的容器&#xff0c;創建完成之后會立馬進入容器。退出之后立馬關閉容器。 docker run -it --namec1 centos:7 /bin/bash退出容器&#xff1a; exit查看現在正在運行的容器命令&#xff1a; docker ps查看歷史容器&#xff0…

docker小白第二天

centos上安裝docker docker官網&#xff0c;docker官網&#xff0c;找到下圖中的doc文檔。 進入如下頁面 選中manuals&#xff0c;安裝docker引擎。 最終centos下的docker安裝文檔鏈接&#xff1a;安裝文檔鏈接. 具體安裝步驟&#xff1a; 1、打開Centos&#xff0c;輸入命…

【BASH】回顧與知識點梳理(十五)

【BASH】回顧與知識點梳理 十五 十五. 指令與文件的搜尋15.1 腳本文件名的搜尋which (尋找『執行檔』) 15.2 文件檔名的搜尋whereis (由一些特定的目錄中尋找文件文件名)locate / updatedbfind與時間有關的選項與使用者或組名有關的參數與文件權限及名稱有關的參數額外可進行的…

JVM垃圾回收

如何確定垃圾 對堆垃圾回收前的第一步就是要判斷哪些對象已經死亡&#xff08;即不能再被任何途徑使用的對象&#xff09; 引用計數法 這個方法就是為對象添加計數器來標識引用個數&#xff0c;計數器為 0 的對象就是不可能再被使用的。但是這種方法存在循環引用問題&#x…

布谷鳥配音:一站式配音軟件

這是一款智能語音合成軟件&#xff0c;可以快速將文字轉換成語音&#xff0c;擁有多種真人模擬發音&#xff0c;可以選擇不同男聲、女聲、童聲&#xff0c;以及四川話、粵語等中文方言和外語配音&#xff0c;并且可對語速、語調、節奏、數字讀法、多音字、背景音等進行全方位設…

less、sass的使用及其區別

CSS預處理器 CSS 預處理器是一種擴展了原生 CSS 的工具&#xff0c;它們添加了一些編程語言的特性&#xff0c;以便更有效地編寫、組織和維護樣式代碼。預處理器允許開發者使用變量、嵌套、函數、混合等功能&#xff0c;從而使 CSS 更具可讀性、可維護性和重用性&#xff0c;特…

學習筆記整理-JS-01-語法與變量

文章目錄 一、語法與變量1. 初識JavaScript2. JavaScript的歷史3. JavaScript與ECMAScript的關系4. JavaScript的體系5. JavaScript的語言風格和特性 二、語法1. JavaScript的書寫位置2. 認識輸出語句3. REPL環境&#xff0c;交互式解析器4. 變量是什么5. 重點內容 一、語法與變…

使用python快速搭建HTTP服務實現局域網網頁瀏覽或文件傳輸

1.使用命令行&#xff08;CMD&#xff09;來快速搭建一個HTTP服務器 你可以借助Python的http.server模塊。以下是在命令行中使用Python快速搭建HTTP服務器的步驟&#xff1a; 打開命令提示符&#xff08;CMD&#xff09;。 進入你想要共享文件的目錄。使用 cd 命令來切換到目…

二、編寫第一個 Spring MVC 程序

文章目錄 一、編寫第一個 Spring MVC 程序 一、編寫第一個 Spring MVC 程序 代碼示例 創建 maven 項目&#xff0c;以此項目為父項目&#xff0c;在父項目的 pom.xml 中導入相關依賴 <dependencies><dependency><groupId>junit</groupId><artifactI…

分支和循環語句(2)(C語言)

目錄 do...while()循環 do語句的語法 do語句的特點 do while循環中的break和continue 練習 goto語句 do...while()循環 do語句的語法 do 循環語句; while(表達式); do語句的特點 循環至少執行一次&#xff0c;使用的場景有限&#xff0c;所以不是經常使用。 #inc…

【uniapp】uniapp自動導入自定義組件和設置分包:

文章目錄 一、自動導入自定義組件&#xff1a;二、設置分包和預加載&#xff1a; 一、自動導入自定義組件&#xff1a; 【Volar 官網】https://github.com/vuejs/language-tools 二、設置分包和預加載&#xff1a; 【官方文檔】https://uniapp.dcloud.net.cn/collocation…

【服務平臺】Rancher運行和管理Docker和Kubernetes,提供管理生產中的容器所需的整個軟件堆棧

Rancher是一個開源軟件平臺&#xff0c;使組織能夠在生產中運行和管理Docker和Kubernetes。使用Rancher&#xff0c;組織不再需要使用一套獨特的開源技術從頭開始構建容器服務平臺。Rancher提供了管理生產中的容器所需的整個軟件堆棧。  完整軟件堆棧 Rancher是供采用容器的團…