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

“`

猜你喜欢

转载自blog.csdn.net/wjj1996825/article/details/80280109