zoukankan      html  css  js  c++  java
  • 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)
          ...
    }
     
     
  • 相关阅读:
    asp.net core 3.1 入口:Program.cs中的Main函数
    vue手机发送验证码倒计时
    阿里云短信服务-短信发送验证码
    前端思维图
    正向代理和反向代理
    lombok+Logback统一异常和日志处理
    java统一结果返回(链式编程结果)
    SpringBoot简介和特点
    web如何测试?
    CSS字体样式属性
  • 原文地址:https://www.cnblogs.com/Im-Victor/p/14134522.html
Copyright © 2011-2022 走看看