解决-Glide You cannot start a load for a destroyed activity

  • 复现步骤
    在Activity的onResume()中使用Glide加载一张背景图片,Glide.with(this).load(url).into(backgroundView)
    然后快速的退出重进这个Activity,多操作几次,应用就Crash,并报java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity

  • 分析
    根据日志,Glide在调用Glide.with(this)执行这行代码时,Activity已经被销毁了,所以Glide抛出了这个异常。
    Glide认为,如果一个Activity被销毁了,就不应该再去加载图片。对于已经在队列中的请求,如果我们使用的是Glide.with(Activity/Fragment),那么Glide会根据Activity/Fragment的生命周期,自动暂停或者取消。如果使用Glide.with(ApplicationContext),Glide并不会绑定Activity/Fragment的生命周期,及时Activity被销毁,仍然会去加载。关于这点的解释,可以看https://stackoverflow.com/questions/31964737/glide-image-loading-with-application-context/32887693#32887693

  • 解决办法
    在调用Glide加载之前增加判断
    if(activity != null && !activity.isFinishing()){//加载图片}

    想看关于这个问题的讨论,可以点击https://github.com/bumptech/glide/issues/803

猜你喜欢

转载自blog.csdn.net/huanglin_developer/article/details/78283286