欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

內(nèi)存泄露導(dǎo)致Android?中setVisibility()?失效原理

 更新時(shí)間:2022年07月03日 08:33:31   作者:??GitLqr????  
這篇文章主要介紹了內(nèi)存泄露導(dǎo)致Android?中setVisibility()?失效原理,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下

一、前情概要

目前,我在開(kāi)發(fā)的一個(gè) Android 項(xiàng)目需要各個(gè)功能做到線(xiàn)上動(dòng)態(tài)化,其中,App 啟動(dòng)時(shí)顯示的 Loading 模塊,會(huì)優(yōu)先檢測(cè)加載遠(yuǎn)程的 Loading 模塊,加載失敗時(shí),會(huì)使用 App 本身默認(rèn)的 Loading 視圖,為此,我編寫(xiě)了一個(gè) LoadingLoader 工具類(lèi):

/**
 * Loading 加載器
 *
 * @author GitLqr
 * @since 2022/7/2
 */
object LoadingLoader {
    private var isInited = false // 防止多次初始化
    private lateinit var onLoadFail: () -> Unit // 遠(yuǎn)程loading加載失敗時(shí)的回調(diào)
    private lateinit var onLoadComplete: () -> Unit // 加載完成后回調(diào)(無(wú)論成功失?。?
    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 工具類(lèi)使用 Kotlin 的單例模式,init() 方法接收 2 個(gè)回調(diào)參數(shù),go() 方法觸發(fā)加載遠(yuǎn)程 Loading 模塊,并根據(jù)加載結(jié)果執(zhí)行回調(diào),其中 isInited 用于防止該工具類(lèi)被初始化多次。然后,在 App 的主入口 LoadingActivity 中使用 LoadingLoader,當(dāng)加載遠(yuǎn)程 Loading 模塊失敗時(shí),將原本隱藏的默認(rèn) Loading 視圖顯示出來(lái);當(dāng)加載 Loading 模塊完成后(無(wú)論成功失?。?,模擬初始化數(shù)據(jù)并跳轉(zhuǎn)主界面,關(guān)閉 LoadingActivity:

/**
 * App 啟動(dòng)時(shí)的 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,會(huì)將 LoadingActivity 界面關(guān)閉,觸發(fā) onDestroy()
            startActivity(intent)
        }, 1000)
    }
}

LoadingActivity 的 xml 布局代碼如下,默認(rèn)的 Loading 布局初始狀態(tài)不可見(jiàn),即 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>

以上代碼比較簡(jiǎn)單,現(xiàn)在來(lái)看下演示效果:

這里會(huì)發(fā)現(xiàn)一個(gè)問(wèn)題,因?yàn)槭且郧蹇諚5姆绞絾?dòng) MainActivity,所以第二次啟動(dòng)時(shí),理論上應(yīng)該會(huì)跟第一次啟動(dòng)時(shí)界面顯示效果完全一致,即每次啟動(dòng)都會(huì)顯示默認(rèn)的 Loading 視圖,但是實(shí)際情況并沒(méi)有,而控制臺(tái)的日志也證實(shí)了 LoadingActivity 的 onDestroy() 有被觸發(fā):

二、摸索過(guò)程

1、代碼執(zhí)行了嗎?

難道第二次啟動(dòng) App 時(shí),LoadingActivity.onLoadFail 沒(méi)有觸發(fā)嗎?加上日志驗(yàn)證一下:

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í)行一遍上面的演示操作,日志輸出如下:

說(shuō)明 2 次啟動(dòng)都是有觸發(fā) LoadingActivity.onLoadFail 的,并且結(jié)果都是 0 ,即 View.VISIBLE。

此時(shí)有點(diǎn)懷疑人生,于是網(wǎng)上找了一圈 setVisibility() 失效 的原因,基本上都是同一個(gè)內(nèi)容(都特么抄來(lái)抄去的),說(shuō)是做動(dòng)畫(huà)導(dǎo)致的,可是我這里并沒(méi)有做動(dòng)畫(huà),所以與網(wǎng)上說(shuō)的情況不相符。

2、視圖不顯示的直接原因是什么?

既然,代碼有輸出日志,那說(shuō)明 setVisibility(View.VISIBLE) 這行代碼肯定執(zhí)行過(guò)了,而界面上不顯示,直接原因是什么?是因?yàn)槟J(rèn) Loading 視圖的 visibility 依舊為 View.GONE?又或者是因?yàn)槠渌蛩貙?dǎo)致 View 的尺寸出現(xiàn)了問(wèn)題?這時(shí),可以使用 AndroidStudio 的 Layout Inspector 工具,可以直觀(guān)的分析界面的布局情況,為了方便 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,會(huì)將 LoadingActivity 界面關(guān)閉,觸發(fā) onDestroy()
//            startActivity(intent)
        }, 1000)
    }
}

然后重復(fù)上述演示操作,第一次啟動(dòng),顯示出默認(rèn) Loading,手動(dòng)按返回鍵退出 App,再第二次啟動(dòng),不顯示默認(rèn) Loading:

控制臺(tái)日志信息也如期輸出,第二次啟動(dòng)確實(shí)執(zhí)行了 setVisibility(View.VISIBLE)

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

這里可以斷定,就是默認(rèn) Loading 視圖的 visibility 依舊為 View.GONE 的情況。

注:因?yàn)?View.GONE 不占據(jù)屏幕空間,所以寬高都為 0,是正常的。

3、操作的視圖是同一個(gè)嗎?

現(xiàn)在回顧一下上述的 2 個(gè)線(xiàn)索,首先,代碼中確定執(zhí)行了 setVisibility(View.VISIBLE),并且日志里也顯示了該視圖的顯示狀態(tài)為 0,即 View.VISIBLE:

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

所以,真相只有一個(gè),日志輸出的視圖 和 Layout Inspector 看到的的視圖,肯定不是同一個(gè)??!為了驗(yàn)證這一點(diǎn),代碼再做如下調(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}")
    }
}

再如上述演示操作一遍,日志輸出如下:

可以看到第二次啟動(dòng)時(shí),LoadingActivity.onLoadFail 中操作的視圖,還是第一次啟動(dòng)時(shí)的那個(gè)視圖,該視圖是通過(guò) findViewById 獲取到的,說(shuō)明 LoadingActivity.onLoadFail 中引用的 Activity 是第一次啟動(dòng)時(shí)的 LoadingActivity,也就是說(shuō) LoadingActivity 發(fā)生內(nèi)存泄露了。此時(shí)才煥然大悟,Kotlin 中的 Lambda 表達(dá)式(像 onLoadFail、onLoadComplete 這種),對(duì)應(yīng)到 Java 中就是匿名內(nèi)部類(lèi),通過(guò) Kotlin Bytecode 再反編譯成 java 代碼可以驗(yàn)證這點(diǎn):

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)部類(lèi)會(huì)持有外部類(lèi)的引用,即匿名內(nèi)部類(lèi)實(shí)例 onLoadFail 持有 LoadingActivity 實(shí)例,而 onLoadFail 又會(huì)通過(guò) LoadingLoader.init() 方法傳遞給 LoadingLoader 這個(gè)單例對(duì)象,所以間接導(dǎo)致 LoadingLoader 持有了 LoadingActivity,因?yàn)閱卫芷谂c整個(gè) App 進(jìn)程相同,所以只要 App 進(jìn)程不死,內(nèi)存中就只有一分 LoadingLoader 實(shí)例,又因?yàn)槭菑?qiáng)引用,所以 GC 無(wú)法回收掉第一次初始化時(shí)傳遞給 LoadingLoader 的 LoadingActivity 實(shí)例,所以,無(wú)論重啟多少次,onLoadFail 中永遠(yuǎn)都是拿著第一次啟動(dòng)時(shí)的 LoadingActivity 來(lái)執(zhí)行 findViewById,拿到的 Loading 視圖自然也不會(huì)是當(dāng)前最新 LoadingActivity 的 Loading 視圖。

三、解決方案

既然知道是因?yàn)?LoadingActivity 內(nèi)存泄露導(dǎo)致的,那么解決方案也簡(jiǎn)單,就是在 LoadingLoader 完成它的使命之后,及時(shí)釋放掉對(duì) LoadingActivity 的引用即可,又因?yàn)?LoadingActivity 實(shí)際上并不是被 LoadingLoader 直接引用,而是被其內(nèi)部變量 onLoadFail 直接引用的,那么在 LoadingLoader 中只需要將 onLoadFail 的引用切斷就行了:

object LoadingLoader {
    private var isInited = false // 防止多次初始化
    private lateinit var onLoadFail: () -> Unit // 遠(yuǎn)程loading加載失敗時(shí)的回調(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() 失效的問(wèn)題就解決掉了

到此這篇關(guān)于內(nèi)存泄露導(dǎo)致Android 中setVisibility() 失效原理的文章就介紹到這了,更多相關(guān)Android setVisibility()失效內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論