Android java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity解決方案


Android項目有時會出現這樣的異常:

java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity
   at com.bumptech.glide.manager.RequestManagerRetriever.assertNotDestroyed(RequestManagerRetriever.java:134)
   at com.bumptech.glide.manager.RequestManagerRetriever.get(RequestManagerRetriever.java:102)
   at com.bumptech.glide.Glide.with(Glide.java:653)
 

原因是:當你的Activity重新創建並且Glide中的context是舊的時,這個問題最容易發生。例如當你有一個CustomAdapter(ArrayList list, Context context),並且在MainActivity或Fragment重新創建時,你不會將新的context傳遞給適配器。然后Glide告訴你我正在使用的context對象不再存在。
解決方案:網上有人給出的解決方案是使用控件的context代替我們傳遞給adapter的context:

Glide.with(holder.itemView.getContext())
                             .load(URL)
                             .skipMemoryCache(true)
                            .placeholder(R.drawable.bg_loading_small)
                            .error(R.drawable.bg_loading_small)
                            .into(nativeAdContentImg)
 

 

但經過測試,這樣做還是不能根本解決問題,有時還是會出現這個異常導致崩潰:最終經過測試發現getApplicationContext()代替掉context比較穩妥

Glide.with(getApplicationContext())
                            .load(URL)
                             .skipMemoryCache(true)
                            .placeholder(R.drawable.bg_loading_small)
                            .error(R.drawable.bg_loading_small)
                            .into(nativeAdContentImg)
 

 

但是 glide加載圖片如果用applicationContext的話,會出現當你離開這個頁面時,圖片的下載工作還在進行,會造成多余的資源消耗,所以可以這樣處理,

// 重寫activity的onDestroy()方法,停止該頁面的glide的加載請求
@override
protected void onDestroy() {
    super.onDestroy();
    Glide.with(getApplicationContext()).pauseRequests();
}
 

如果是在actiity中做glide加載的話,可以做如下判斷:


if (!YourActivity.this.isFinishing()) {
  Glide.with(YourActivity.this)
      .load(URL)
      ...
}
 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM