当前位置: 首页 > news >正文

Android Glide应用中遇到问题

1. 导入库

build.gradle中添加glide库,kotlin用kapt,java用annotationProcessor

dependencies {
    implementation 'com.github.bumptech.glide:glide:4.13.2'
    kapt 'com.github.bumptech.glide:compiler:4.13.2'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.13.2'
}

ProjectGlideModule继承AppGlideModule,需要添加GlideModule注释。applyOptions方法中可以对builder进行全局配置。

@GlideModule
class ProjectGlideModule : AppGlideModule() {

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        super.applyOptions(context, builder)
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
    }
    
}

2. OKHttp配置

Glide 默认的请求网络框架是HttpURLConnection,想要改成OkHttp就需要用到registerComponents函数。首先需要导入okhttp3-integration

implementation 'com.github.bumptech.glide:okhttp3-integration:4.13.2'

registerComponents函数内调用Registryreplace方法替代网络请求框架。

override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
    super.registerComponents(context, glide, registry)

    registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(NetworkUtil.getOKHttpClient()))
}

3. 自定义模型

在实际项目中,我们往往会有一些特殊需要。比如我们通过url返回图片的字节流,还需要Base64解码才能使用。

  • 定义GlideDownloadPic类,继承com.bumptech.glide.load.Key,需要实现updateDiskCacheKey函数
    class GlideDownloadPic(val picUrl: String) : Key {
        private var mGlideUrl = GlideUrl(picUrl)
    
        override fun updateDiskCacheKey(messageDigest: MessageDigest) {
            mGlideUrl.updateDiskCacheKey(messageDigest)
        }
    
    }
    
  • 定义GlideDownloadPicModelLoader,继承ModelLoaderFactory继承ModelLoaderFactory,在后面注册时使用。buildLoadData函数用来获取图片数据。
    class GlideDownloadPicModelLoader : ModelLoader<GlideDownloadPic, InputStream> {
    
        class Factory : ModelLoaderFactory<GlideDownloadPic, InputStream> {
    
            override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<GlideDownloadPic, InputStream> {
                return GlideDownloadPicModelLoader()
            }
    
            override fun teardown() {
            }
    
        }
    
        override fun buildLoadData(
            model: GlideDownloadPic,
            width: Int,
            height: Int,
            options: Options
        ): ModelLoader.LoadData<InputStream>? {
            return ModelLoader.LoadData(model, GlideDownloadPicDataFetcher(model))
        }
    
        override fun handles(model: GlideDownloadPic): Boolean {
            return true
        }
    
    }
    
  • 定义GlideDownloadPicDataFetcher,继承DataFetcher
    class GlideDownloadPicDataFetcher(downloadPic: GlideDownloadPic) : DataFetcher<InputStream> {
    
        private var mDownloadPic = downloadPic
    
        override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in InputStream>) {
            downloadPic(mDownloadPic.picUrl, {
                callback.onDataReady(ByteArrayInputStream(Base64.decode(it, Base64.DEFAULT)))
            }, {
                callback.onLoadFailed(it)
            })
        }
    
        // 下载图片
        private fun downloadPic(picUrl: String, onSuccess:(ByteArray) -> Unit, onFail:(Exception) -> Unit) {
            if (picUrl.startsWith("http")) {
                NetworkUtil.getOKHttpClient()
                    .newCall(Request.Builder().url(picUrl).build())
                    .enqueue(object : Callback{
                        override fun onResponse(call: Call, response: Response) {
                            if (response.isSuccessful) {
                                var bodyByteArray = response.body()?.bytes()
                                if (bodyByteArray != null) {
                                    onSuccess(bodyByteArray)
                                    return
                                }
                            }
                            onFail(IOException("wrong url $picUrl"))
                        }
    
                        override fun onFailure(call: Call, e: IOException) {
                            onFail(IOException("wrong url $picUrl"))
                        }
                    })
            } else {
                onFail(IOException("wrong url $picUrl"))
            }
        }
    
        override fun getDataClass(): Class<InputStream> {
            return InputStream::class.java
        }
    
        override fun cleanup() {
        }
    
        override fun getDataSource(): DataSource {
            return DataSource.REMOTE
        }
    
        override fun cancel() {
        }
    }
    
  • registerComponents函数内注册
    registry.replace(GlideDownloadPic::class.java, InputStream::class.java,
            GlideDownloadPicModelLoader.Factory())
    
  • 使用自定义模型
    Glide.with(this).load(GlideDownloadPic("xxx.jpg"))
            .error(getDrawable(R.drawable.xxx))
            .into(findViewById(R.id.image_view))
    

源码下载: https://github.com/nai-chen/AndroidBlog

相关文章:

  • 个人云服务的搭建(折腾)之旅
  • 浅谈js中的深拷贝和浅拷贝
  • Hbase-3-4-Hbase读写数据流程
  • Oracle——常用的几种函数(含案例)
  • 【Linux】多线程 —— 线程概念 | 线程控制
  • windows10创建ssh git gitee使用公钥私钥【自留收藏】
  • 微信搜题接口API功能
  • YBTOJ 树状数组 二进制
  • 无胁科技-TVD每日漏洞情报-2022-8-30
  • Java8 特性(一):函数、Lambok、Stream
  • 定时器(Quartz)
  • 神经网络实现线性回归,神经网络是回归算法吗
  • MFC调用VLC库播放中文路径导致崩溃的问题
  • 微信公众号搜题功能接口
  • 5.java不同方法的区别(构造方法,实例方法,类方法,static关键字)
  • 002-读书笔记-JavaScript高级程序设计 在HTML中使用JavaScript
  • Brief introduction of how to 'Call, Apply and Bind'
  • iOS编译提示和导航提示
  • Java IO学习笔记一
  • Java 内存分配及垃圾回收机制初探
  • jdbc就是这么简单
  • Python利用正则抓取网页内容保存到本地
  • spring学习第二天
  • Web设计流程优化:网页效果图设计新思路
  • 从零搭建Koa2 Server
  • 海量大数据大屏分析展示一步到位:DataWorks数据服务+MaxCompute Lightning对接DataV最佳实践...
  • 配置 PM2 实现代码自动发布
  • 什么软件可以剪辑音乐?
  • 使用common-codec进行md5加密
  • const的用法,特别是用在函数前面与后面的区别
  • PostgreSQL 快速给指定表每个字段创建索引 - 1
  • Spark2.4.0源码分析之WorldCount 默认shuffling并行度为200(九) ...
  • ​人工智能书单(数学基础篇)
  • # MySQL server 层和存储引擎层是怎么交互数据的?
  • ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLTr
  • #我与Java虚拟机的故事#连载05:Java虚拟机的修炼之道
  • (06)金属布线——为半导体注入生命的连接
  • (react踩过的坑)Antd Select(设置了labelInValue)在FormItem中initialValue的问题
  • (二十一)devops持续集成开发——使用jenkins的Docker Pipeline插件完成docker项目的pipeline流水线发布
  • (算法)Game
  • (转)Android中使用ormlite实现持久化(一)--HelloOrmLite
  • (转)C#开发微信门户及应用(1)--开始使用微信接口
  • (转)Java socket中关闭IO流后,发生什么事?(以关闭输出流为例) .
  • (转载)hibernate缓存
  • .NET CF命令行调试器MDbg入门(一)
  • .Net Remoting(分离服务程序实现) - Part.3
  • .NET 中使用 Mutex 进行跨越进程边界的同步
  • .net(C#)中String.Format如何使用
  • .Net6支持的操作系统版本(.net8已来,你还在用.netframework4.5吗)
  • @RequestBody与@ModelAttribute
  • @transactional 方法执行完再commit_当@Transactional遇到@CacheEvict,你的代码是不是有bug!...
  • @Valid和@NotNull字段校验使用
  • [ vulhub漏洞复现篇 ] JBOSS AS 4.x以下反序列化远程代码执行漏洞CVE-2017-7504
  • []指针
  • [20171102]视图v$session中process字段含义