Android(安卓)java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity解决方案
16lz
2022-06-12
Android项目在使用Glide有时会出现这样的异常:
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的加载请求@overrideprotected void onDestroy() { super.onDestroy(); Glide.with(getApplicationContext()).pauseRequests();}
如果是在actiity中做glide加载的话,可以做如下判断:
if (!YourActivity.this.isFinishing()) { Glide.with(YourActivity.this) .load(URL) ...}
参考于:
https://blog.csdn.net/wjj1996825/article/details/80280109
Glide用法:https://www.cnblogs.com/guilin-hu/p/5706916.html
更多相关文章
- android下拉菜单spinner的使用方法
- Android(安卓)开发 全局捕获异常
- Android(安卓)SharedPreferences的使用
- Android(安卓)Fastboot源码分析
- Android(安卓)DownloadManager 使用
- Android(安卓)Action使用实例
- 箭头函数的基础使用
- NPM 和webpack 的基础使用
- Python list sort方法的具体使用