內(nèi)存泄露導(dǎo)致Android?中setVisibility()?失效原理
一、前情概要
目前,我在開發(fā)的一個 Android 項目需要各個功能做到線上動態(tài)化,其中,App 啟動時顯示的 Loading 模塊,會優(yōu)先檢測加載遠(yuǎn)程的 Loading 模塊,加載失敗時,會使用 App 本身默認(rèn)的 Loading 視圖,為此,我編寫了一個 LoadingLoader 工具類:
/**
* Loading 加載器
*
* @author GitLqr
* @since 2022/7/2
*/
object LoadingLoader {
private var isInited = false // 防止多次初始化
private lateinit var onLoadFail: () -> Unit // 遠(yuǎn)程loading加載失敗時的回調(diào)
private lateinit var onLoadComplete: () -> Unit // 加載完成后回調(diào)(無論成功失?。?
fun init(onLoadFail: () -> Unit = {}, onLoadComplete: () -> Unit = {}): LoadingLoader {
if (!isInited) {
this.onLoadFail = onLoadFail
this.onLoadComplete = onLoadComplete
isInited = true
} else {
log("you have inited, this time is not valid")
}
return this
}
fun go() {
if (isInited) {
loadRemoteLoading(callback = { isSuccess ->
if (!isSuccess) onLoadFail()
onLoadComplete()
})
} else {
log("you must invoke init() firstly")
}
}
private fun loadRemoteLoading(callback: (boolean: Boolean) -> Unit) {
// 模擬遠(yuǎn)程 Loading 模塊加載失敗
Handler(Looper.getMainLooper()).postDelayed({
callback(false)
}, 1000)
}
private fun log(msg: String) {
Log.e("LoadingUpdater", msg)
}
}LoadingLoader 工具類使用 Kotlin 的單例模式,init() 方法接收 2 個回調(diào)參數(shù),go() 方法觸發(fā)加載遠(yuǎn)程 Loading 模塊,并根據(jù)加載結(jié)果執(zhí)行回調(diào),其中 isInited 用于防止該工具類被初始化多次。然后,在 App 的主入口 LoadingActivity 中使用 LoadingLoader,當(dāng)加載遠(yuǎn)程 Loading 模塊失敗時,將原本隱藏的默認(rèn) Loading 視圖顯示出來;當(dāng)加載 Loading 模塊完成后(無論成功失?。M初始化數(shù)據(jù)并跳轉(zhuǎn)主界面,關(guān)閉 LoadingActivity:
/**
* App 啟動時的 Loading 界面
*
* @author GitLqr
* @since 2022/7/2
*/
class LoadingActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_loading)
// Loading 模塊加載器
LoadingLoader.init(onLoadFail, onLoadComplete).go()
}
override fun onDestroy() {
super.onDestroy()
Log.e("GitLqr", "onDestroy")
}
private val onLoadFail: () -> Unit = {
// 顯示默認(rèn) loading 界面
findViewById<View>(R.id.cl_def_loading).setVisibility(View.VISIBLE)
}
private val onLoadComplete: () -> Unit = {
// 模擬初始化數(shù)據(jù),1秒后跳轉(zhuǎn)主界面
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
// 注意:此處意圖使用的 flag,會將 LoadingActivity 界面關(guān)閉,觸發(fā) onDestroy()
startActivity(intent)
}, 1000)
}
}LoadingActivity 的 xml 布局代碼如下,默認(rèn)的 Loading 布局初始狀態(tài)不可見,即 visibility="gone":
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/cl_def_loading"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f00"
android:visibility="gone"
tools:visibility="visible">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="很好看的默認(rèn)loading界面"
android:textColor="@color/white"
android:textSize="60dp" />
<ProgressBar
android:id="@+id/pb_loading"
android:layout_width="0dp"
android:layout_height="0dp"
android:indeterminateDrawable="@drawable/anim_loading"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.75"
app:layout_constraintWidth_percent="0.064" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
以上代碼比較簡單,現(xiàn)在來看下演示效果:

這里會發(fā)現(xiàn)一個問題,因為是以清空棧的方式啟動 MainActivity,所以第二次啟動時,理論上應(yīng)該會跟第一次啟動時界面顯示效果完全一致,即每次啟動都會顯示默認(rèn)的 Loading 視圖,但是實際情況并沒有,而控制臺的日志也證實了 LoadingActivity 的 onDestroy() 有被觸發(fā):

二、摸索過程
1、代碼執(zhí)行了嗎?
難道第二次啟動 App 時,LoadingActivity.onLoadFail 沒有觸發(fā)嗎?加上日志驗證一下:
class LoadingActivity : AppCompatActivity() {
...
private val onLoadFail: () -> Unit = {
// 顯示默認(rèn) loading 界面
val defLoading = findViewById<View>(R.id.cl_def_loading)
defLoading.setVisibility(View.VISIBLE)
Log.e("GitLqr", "defLoading.setVisibility --> ${defLoading.visibility}")
}
}重新打包再執(zhí)行一遍上面的演示操作,日志輸出如下:

說明 2 次啟動都是有觸發(fā) LoadingActivity.onLoadFail 的,并且結(jié)果都是 0 ,即 View.VISIBLE。
此時有點懷疑人生,于是網(wǎng)上找了一圈
setVisibility() 失效的原因,基本上都是同一個內(nèi)容(都特么抄來抄去的),說是做動畫導(dǎo)致的,可是我這里并沒有做動畫,所以與網(wǎng)上說的情況不相符。
2、視圖不顯示的直接原因是什么?
既然,代碼有輸出日志,那說明 setVisibility(View.VISIBLE) 這行代碼肯定執(zhí)行過了,而界面上不顯示,直接原因是什么?是因為默認(rèn) Loading 視圖的 visibility 依舊為 View.GONE?又或者是因為其他因素導(dǎo)致 View 的尺寸出現(xiàn)了問題?這時,可以使用 AndroidStudio 的 Layout Inspector 工具,可以直觀的分析界面的布局情況,為了方便 Layout Inspector 工具獲取 LoadingActivity 的布局信息,需要將 LoadingActivity.onLoadComplete 中跳轉(zhuǎn)主界面的代碼注釋掉,其他保持不變:
class LoadingActivity : AppCompatActivity() {
...
private val onLoadComplete: () -> Unit = {
// 模擬初始化數(shù)據(jù),1秒后跳轉(zhuǎn)主界面
Handler(Looper.getMainLooper()).postDelayed({
// val intent = Intent(this, MainActivity::class.java)
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
// // 注意:此處意圖的 flag,會將 LoadingActivity 界面關(guān)閉,觸發(fā) onDestroy()
// startActivity(intent)
}, 1000)
}
}然后重復(fù)上述演示操作,第一次啟動,顯示出默認(rèn) Loading,手動按返回鍵退出 App,再第二次啟動,不顯示默認(rèn) Loading:

控制臺日志信息也如期輸出,第二次啟動確實執(zhí)行了 setVisibility(View.VISIBLE):

這時,使用 Layout Inspector(菜單欄 -> Tools -> Layout Inspector),獲取到 LoadingActivity 的布局信息:

這里可以斷定,就是默認(rèn) Loading 視圖的 visibility 依舊為 View.GONE 的情況。
注:因為 View.GONE 不占據(jù)屏幕空間,所以寬高都為 0,是正常的。
3、操作的視圖是同一個嗎?
現(xiàn)在回顧一下上述的 2 個線索,首先,代碼中確定執(zhí)行了 setVisibility(View.VISIBLE),并且日志里也顯示了該視圖的顯示狀態(tài)為 0,即 View.VISIBLE:

其次,使用 Layout Inspector 看到的的視圖狀態(tài)卻為 View.GONE:

所以,真相只有一個,日志輸出的視圖 和 Layout Inspector 看到的的視圖,肯定不是同一個??!為了驗證這一點,代碼再做如下調(diào)整,分別在 onCreate() 和 onLoadFail 中打印默認(rèn) Loading 視圖信息:
class LoadingActivity : AppCompatActivity() {
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_loading)
val defLoading = findViewById<View>(R.id.cl_def_loading)
Log.e("GitLqr", "onCreate ---> view is ${defLoading}")
// Loading 模塊加載器
LoadingLoader.init(onLoadFail, onLoadComplete).go()
}
private val onLoadFail: () -> Unit = {
// 顯示默認(rèn) loading 界面
val defLoading = findViewById<View>(R.id.cl_def_loading)
defLoading.setVisibility(View.VISIBLE)
Log.e("GitLqr", "defLoading.setVisibility --> ${defLoading.visibility}, view is ${defLoading}")
}
}再如上述演示操作一遍,日志輸出如下:

可以看到第二次啟動時,LoadingActivity.onLoadFail 中操作的視圖,還是第一次啟動時的那個視圖,該視圖是通過 findViewById 獲取到的,說明 LoadingActivity.onLoadFail 中引用的 Activity 是第一次啟動時的 LoadingActivity,也就是說 LoadingActivity 發(fā)生內(nèi)存泄露了。此時才煥然大悟,Kotlin 中的 Lambda 表達(dá)式(像 onLoadFail、onLoadComplete 這種),對應(yīng)到 Java 中就是匿名內(nèi)部類,通過 Kotlin Bytecode 再反編譯成 java 代碼可以驗證這點:
public final class LoadingActivity extends AppCompatActivity {
private final Function0 onLoadFail = (Function0)(new Function0() {
// $FF: synthetic method
// $FF: bridge method
public Object invoke() {
this.invoke();
return Unit.INSTANCE;
}
public final void invoke() {
View defLoading = LoadingActivity.this.findViewById(1000000);
defLoading.setVisibility(0);
StringBuilder var10001 = (new StringBuilder()).append("defLoading.setVisibility --> ");
Intrinsics.checkExpressionValueIsNotNull(defLoading, "defLoading");
Log.e("GitLqr", var10001.append(defLoading.getVisibility()).append(", view is ").append(defLoading).toString());
}
});
private final Function0 onLoadComplete;
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(1300004);
View defLoading = this.findViewById(1000000);
Log.e("GitLqr", "onCreate ---> view is " + defLoading);
LoadingLoader.INSTANCE.init(this.onLoadFail, this.onLoadComplete).go();
}
protected void onDestroy() {
super.onDestroy();
Log.e("GitLqr", "onDestroy");
}
public LoadingActivity() {
this.onLoadComplete = (Function0)null.INSTANCE;
}
}我們知道,Java 中,匿名內(nèi)部類會持有外部類的引用,即匿名內(nèi)部類實例 onLoadFail 持有 LoadingActivity 實例,而 onLoadFail 又會通過 LoadingLoader.init() 方法傳遞給 LoadingLoader 這個單例對象,所以間接導(dǎo)致 LoadingLoader 持有了 LoadingActivity,因為單例生命周期與整個 App 進(jìn)程相同,所以只要 App 進(jìn)程不死,內(nèi)存中就只有一分 LoadingLoader 實例,又因為是強(qiáng)引用,所以 GC 無法回收掉第一次初始化時傳遞給 LoadingLoader 的 LoadingActivity 實例,所以,無論重啟多少次,onLoadFail 中永遠(yuǎn)都是拿著第一次啟動時的 LoadingActivity 來執(zhí)行 findViewById,拿到的 Loading 視圖自然也不會是當(dāng)前最新 LoadingActivity 的 Loading 視圖。
三、解決方案
既然知道是因為 LoadingActivity 內(nèi)存泄露導(dǎo)致的,那么解決方案也簡單,就是在 LoadingLoader 完成它的使命之后,及時釋放掉對 LoadingActivity 的引用即可,又因為 LoadingActivity 實際上并不是被 LoadingLoader 直接引用,而是被其內(nèi)部變量 onLoadFail 直接引用的,那么在 LoadingLoader 中只需要將 onLoadFail 的引用切斷就行了:
object LoadingLoader {
private var isInited = false // 防止多次初始化
private lateinit var onLoadFail: () -> Unit // 遠(yuǎn)程loading加載失敗時的回調(diào)
private lateinit var onLoadComplete: () -> Unit // 加載完成后回調(diào)
fun go() {
if (isInited) {
loadRemoteLoading(callback = { isSuccess ->
if (!isSuccess) onLoadFail()
onLoadComplete()
destroy() // 使命完成,釋放資源
})
} else {
log("you must invoke init() firstly")
}
}
fun destroy() {
this.onLoadFail = {}
this.onLoadComplete = {}
this.isInited = false
}
}至此,因內(nèi)存泄露導(dǎo)致 setVisibility() 失效的問題就解決掉了
到此這篇關(guān)于內(nèi)存泄露導(dǎo)致Android 中setVisibility() 失效原理的文章就介紹到這了,更多相關(guān)Android setVisibility()失效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android添加用戶組及自定義App權(quán)限的方法
今天小編就為大家分享一篇Android添加用戶組及自定義App權(quán)限的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Android 網(wǎng)絡(luò)圖片查看器與網(wǎng)頁源碼查看器
本篇文章主要介紹了Android 網(wǎng)絡(luò)圖片查看器與網(wǎng)頁源碼查看器的相關(guān)知識。具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04
創(chuàng)建Android庫的方法及Android .aar文件用法小結(jié)
本文給大家介紹了創(chuàng)建Android庫的方法及Android中 .aar文件生成方法與用法詳解,涉及到創(chuàng)建庫模塊操作步驟及開發(fā)注意事項,需要的朋友參考下吧2017-12-12
Android 下載網(wǎng)絡(luò)圖片并顯示到本地
本文主要介紹了Android實現(xiàn)下載網(wǎng)絡(luò)圖片并顯示到本地功能的示例代碼。具有很好的參考價值,下面跟著小編一起來看下吧2017-03-03
Android Data Binding數(shù)據(jù)綁定詳解
本文主要介紹Android Data Binding數(shù)據(jù)綁定的知識,這里整理了詳細(xì)的資料及簡單示例代碼幫助大家學(xué)習(xí)理解此部分知識,有需要的小伙伴可以參考下2016-09-09
Android開發(fā)之在程序中時時獲取logcat日志信息的方法(附demo源碼下載)
這篇文章主要介紹了Android開發(fā)之在程序中時時獲取logcat日志信息的方法,結(jié)合實例形式較為詳細(xì)的分析了實時獲取logcat日志的原理、步驟與相關(guān)實現(xiàn)技巧,并附帶相應(yīng)的demo源碼供讀者下載參考,需要的朋友可以參考下2016-02-02
Android實現(xiàn)支持進(jìn)度條顯示的短信備份工具類
這篇文章主要介紹了Android實現(xiàn)支持進(jìn)度條顯示的短信備份工具類,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-03-03

