深入 Glide 源码探究解决加载图片超时问题

Glide无法加载https图片的完全解决方案 在项目当中出现加载https图片失败,但是将图片url直接复制到浏览器是可以正常访问的,如果你也是出现类似问题可以参考如下解决方案。 首先出现这个问题基本上是由于https协议必须要有CA证书才可以访问,所以问题本质是进行网络访问过程中没有CA证书导致的,所以首先我们要做的是需要把图片https所对应的CA证书下载下来 我在项目当中使用Glide的版本是 implementation 'com.github.bumptech.glide:glide:4.11.0' annotationProcess 阅读详情

What happened

我们的项目是一个图片浏览的 App,为了用户有良好的体验效果,会定时在后台下载壁纸数据,且同时会将对应的图片提前下载到本地,等到用户打开App时,不需要再等待图片下载,就可以立即看到图片。但在开发和测试的过程中,会出现下载图片超时错误的情况,而且在最近一次需求中,出现的概率大大增加,所以决心深入 Glide 源码探究。

下载超时 log:

GlideHelper: img download error. url = https://xxxx/wbp,q_auto,h_2276,w_1080,c_fill/https%3A%2F%2Fcdn.xxx.com%2Fstatic%2Fwallpaper%2F3518313389605031946_GETTY_996206592.jpg%3Fut%3D1624552936 
    java.util.concurrent.ExecutionException: java.net.SocketTimeoutException : Read timed out
        at com.bumptech.glide.request.RequestFutureTarget.doGet(RequestFutureTarget.java:189)
        at com.bumptech.glide.request.RequestFutureTarget.get(RequestFutureTarget.java:100)
        at com.xxx.common.glide.GlideHelper.download(GlideHelper.java:61)
        at com.xxx.manager.KSyncStrategyManager.downloadWallpapers(KSyncStrategyManager.java:239)
        at com.xxx.manager.KSyncStrategyManager.startDownloadWallpaperJobs(KSyncStrategyManager.java:60)
        at com.xxx.manager.KSyncStrategyManager.startSyncWallpaperListByUserLikeTag(KSyncStrategyManager.java:117)
        ...

源码分析

先附上我总结的整个源码分析的逻辑图,以下是分析的过程,可能会有冗长,如果想知道如何设置超时时间,可以直接跳到解决方案。

流程图.jpg
由于我们对 Glide 进行了升级,我对旧版本(3.7.0)和新版本(4.13.0)都进行了分析,两个版本区别不是特别大,以下主要以 4.13.0 来做分析的,最后会把有区别的地方标记在逻辑图中。

我们项目中调用 Glide 的 downloadOnly() 去下载图片:

public static File download(Context context, String url, int timeout) {
   
   
    ...

    File file = null;

    try {
   
   
        file = Glide.with(context)
                .load(glideUrl)
                .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                .get();

    } catch (Exception e) {
   
   
        LogUtils.e(TAG, "img download error. url = " + url, e);
    }
    return file;
}

首先,我的方式是从 Glide.xxx.get() 开始分析,接下来会调用到 RequestFutureTarget 中的 doGet(xxx),其中是获取 resource,没有涉及到 SocketTimeoutException 相关超时异常,所以我们还得往上一层去追。

public class RequestFutureTarget<R> implements FutureTarget<R>, RequestListener<R> {
   
   
  ...

  @Override
  public R get() throws InterruptedException, ExecutionException {
   
   
    try {
   
   
      return doGet(null);
    } catch (TimeoutException e) {
   
   
      throw new AssertionError(e);
    }
  }

  ...

  private synchronized R doGet(Long timeoutMillis) throws ExecutionException, InterruptedException, TimeoutException {
   
   

    if (assertBackgroundThread && !isDone()) {
   
   
      Util.assertBackgroundThread();
    }

    if (isCancelled) {
   
   
      throw new CancellationException();
    } else if (loadFailed) {
   
   
      throw new ExecutionException(exception);
    } else if (resultReceived) {
   
   
      return resource;
    }

    // 省略了异常判断
    ...

    return resource;
  }
}

紧接着就开始分析 submit(xxx),它会调用到 RequestBuilder 中 submit(xxx),最终调用到 4 个参数的 into(xxx),通过一步一步分析,其中调用另一个类 RequestManager.track(xxx),最终会调用到 RequestTracker.runRequest(xxx),从方法名看感觉像是开始执行请求操作了。

public class RequestBuilder<TranscodeType> extends BaseRequestOptions<RequestBuilder<TranscodeType>> implements Cloneable, ModelTypes<RequestBuilder<TranscodeType>> {
   
   
    ...
    
    public FutureTarget<TranscodeType> submit(int width, int height) {
   
   
        final RequestFutureTarget<TranscodeType> target = new RequestFutureTarget<>(width, height);
        return into(target, target, Executors.directExecutor());
    }

    private <Y extends Target<TranscodeType>> Y into(
            @NonNull Y target,
            @Nullable RequestListener<TranscodeType> targetL
Glide图片加载优化全攻略:从缓存到性能调优 如果需要调整 Glide 的线程池大小,可以通过自定义。 阅读详情

相关推荐

Glide加载Gif的卡顿优化思路分析,从基础到源码统统帮你搞定

// clear all pixels when meet first frame and drop prev image from last loop if (previousFrame == null) { if (previousImage != null) { // 回收上一帧的Bitmap bitmapProvider.release(previousImage); } previousImage = null; // 并且将Bitmap的像素填充黑色 Arrays.fill(dest, COLO

m0_61417997的博客 718

Glide源码学习八:实现带进度的Glide图片加载功能

相关文章:=====扩展目标====首先来确立一下功能扩展的目标。虽说Glide本身就已经十分强大了,但是有一个功能却长期以来都不支持,那就是监听下载进度功能。我们都知道,使用Glide来加载一张网络上的图片是非常简单的,但是让人头疼的是,我们却无从得知当前图片的下载进度。如果这张图片很小的话,那么问题也不大,反正很快就会被加载出来。但如果这是一张比较大的GIF图,用户耐心等了很久结果图片还没显示出来,这个时候你就会觉得下载进度功能是十分有必要的了。

2301_77595001的博客 924

Glide-加载本地图片

前言:这一节我们将介绍Glide如何加载本地图片Glide 系列目录 1.Glide-入门教程 2.Glide-占位图以及加载动画 3.Glide-加载本地图片 1.在清单文件中增加权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 2.加载其实Glide加载本地图片和加载网络图片调用的方法是一样

夏雨 8万+

Glide加载图片流程(Part One)

由于项目的需要,这几天对Glide的执行过程做了简单的了解,希望对想了解Glide基本用法的朋友能有所帮助。注意 此系列博客基于Glide V3.7.0版本源码 这里假设朋友们能够在Android Studio中正确引入Glide相关的依赖,如果有不懂的朋友,请参考官方文档引入依赖。 为了让朋友们尽快的了解Glide加载图片的流程,我们就从最简单的方式入手。请看如下代码:ImageView ful

行者录 1万+

Glide源码学习八:实现带进度的Glide图片加载功能,android基础开发

由于题目很多整理答案的工作量太大,所以仅限于提供知识点,详细的很多问题和参考答案我都整理成了 PDF文件《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取![外链图片转存中…(img-gey0VIym-1712538755727)][外链图片转存中…(img-mVAxdysL-1712538755727)][外链图片转存中…(img-UmV6TIYU-1712538755727)]

2401_84149557的博客 1080

最新源码Glide4.12框架之加载图片流程源码分析

一、前言 Android图片加载框架,在android应用开发中是一个常见的话题。在12、13年的时候我记得可能用的最多的是XUtils的一套框架(更早之前叫aFinal框架),这个框架中提供imageUtils用于在android应用的开发中完成远程图片的加载。再后来呢,有Picasso、Fresco、Glide。而这几年的开发经验来看,Glide最为流行。不信,可以查看github上项目地址,分别对比对比watch数、fork数、star数,就能确定Glide确实最为流行。 如何对图片框架技术进行选型?

HYM BLOG 2401

深入解析Glide源码:Android图片加载的实现

在图片加载过程中,Glide提供了丰富的加载选项,通过类来设置,以便于开发者根据实际需求定制加载行为。Glide的加载选项包括但不限于:图像尺寸、缓存策略、解码类型等。// 代码块展示了如何使用RequestOptions自定义图片加载行为.override(100, 100) // 设置加载图片的尺寸.centerCrop() // 设置图片的裁剪方式// 设置磁盘缓存策略。

weixin_35257663的博客 1042

SpringBoot实战——仿b站项目(一)

热部署就是当应用程序这种运行的时候升级冉家或者修改某一部分代码、配置文件时,无需手动启动应用,即可修改的部分生效工具 + IDEA配置。

weixin_52880572的博客 3456

Matlab实战:从零搭建弹道导弹六自由度仿真模型(附完整代码)

本文详细介绍了如何使用Matlab从零搭建弹道导弹六自由度仿真模型,涵盖仿真环境配置、核心运动方程实现、气动力建模及仿真结果分析。通过完整代码示例,帮助读者掌握弹道导弹六自由度仿真的关键技术,适用于航空航天工程和复杂系统建模领域。

x8y9z0的博客 947

CCS安装教程图解说明:可视化步骤快速上手

通过清晰的图解步骤详解CCS安装过程,帮助新手快速掌握环境搭建。结合ccs安装教程与实际操作界面,每一步都直观易懂,大幅降低学习门槛,提升配置效率。

weixin_42611310的博客 963

UReport2 报表设计器 在线表格

UReport2官网 一、UReport2报表设计器 UReport2是一个开源的可视化报表设计器,功能强大,操作简单,可以实现复杂的报表统计,有各种各样的导出和打印功能,支持导入Excel表格! 1、报表设计器 2、设计一个简单的用户列表展示 二、可编辑表格 扩展了layui的表格,支持多元化数据编辑(单选,多些、日期、下拉联动),开发简单、高效、便捷。有了它就可以轻松开发类似进销存系统的表格录入功能了,用户拿来即用! 三、主从表录......

ejinxian的专栏 2万+

C++11并发与多线程笔记(2) 线程启动、结束,创建线程多法、join,detach

第二节 线程启动、结束,创建线程多法、join,detach 一、范例演示线程运行的开始 程序运行起来,生成一个进程,该进程所属的主线程开始自动运行;当主线程从main()函数返回,则整个进程执行完毕 主线程从main()开始执行,那么我们自己创建的线程,也需要从一个函数开始运行(初始函数),一旦这个函数运行完毕,线程也结束运行 整个进程是否执行完毕的标志是:主线程是否执行完,如果主线程执行完毕了,就代表整个进程执行完毕了,此时如果其他子线程还没有执行完,也会被强行终止【此条有例外,以后会解释】 创建

qq_38231713的博客 1万+

游戏数据训练世界模型:AI物理规律学习与仿真应用实践

世界模型作为理解现实世界动态的AI工具,通过多模态数据学习物理和空间属性来预测未来状态。其核心原理在于从环境交互中提取物理规律,技术价值体现在能够安全、低成本地训练AI系统应对复杂场景。在应用层面,游戏数据因其结构化环境和内置物理引擎,成为世界模型训练的优质素材。游戏世界中的物体交互、运动轨迹等数据天然包含现实物理规律,特别适合训练物理AI。本文以General Intuition公司获得3.2亿美元融资为切入点,深入探讨游戏数据在世界模型训练中的技术实现路径,涵盖数据提取管道构建、多模态数据融合方法,以及

weixin_29056865的博客 367

PyTorch 最新安装教程(2021-07-27)

PyTorch 最新安装教程(2021-07-27)前言1. 安装 Anaconda2. 检查显卡,更新驱动3. 创建PyTorch环境4. 配置清华TUNA镜像源5. 安装 PyTorch6. 测试 前言 万事开头难! 这句话又一次被我验证。 记得前不久刚陷入Tensorflow2.0的安装困境,这一次又被PyTorch 搞哭辽。 孩子太难了o(╥﹏╥)o,不过还好最终成功安装,感谢全网资源,感谢大佬们的博客!被我一次一次试了出来。 1. 安装 Anaconda Anaconda 是一个用于科学计算的 P

全网粉丝30W+,优快云、稀土掘金人工智能领域签约作者,人工智能、大模型、Python 爬虫,商务合作,请私信沟通。 23万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

上一篇: 从 ExoPlayer 源码分析视频无法播放问题
零一Chat
博客等级 码龄11年 2粉丝 5原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值