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)
      ...
}
 

 

 
posted @   mingruqi  阅读(1911)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2018-12-14 android代码混淆
点击右上角即可分享
微信分享提示