每天记录学习的新知识 : AppGlideModule_清风徐来辽的博客-程序员秘密

技术标签: AppGlideModule  android  Android  

AppGlideModule 是什么?

AppGlideModule就是Glide的全局配置文件,4.0以上添加的,之前是 GlideModule

https://muyangmin.github.io/glide-docs-cn/javadocs/400/com/bumptech/glide/module/AppGlideModule.html

配置 AppGlideModule

Glide 4.10 以上的版本必须配置

@GlideModule
public class GlideConfigModule extends AppGlideModule {
    

    private static final String TAG = "GlideConfigModule";

    /**
     * 配置图片缓存的路径和缓存空间的大小
     */
    @Override
    public void applyOptions(@NonNull final Context context, GlideBuilder builder) {
    

    }

    @Override
    public boolean isManifestParsingEnabled() {
    
        return false;
    }

    /**
     * 注册指定类型的源数据,并指定它的图片加载所使用的 ModelLoader
     */
    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, Registry registry) {
    
        AppLogUtils.i(TAG, "registerComponents");
    }

}
        <meta-data
            android:name=".datamodle.glide.GlideConfigModule"
            android:value="AppGlideModule" />

混淆:

################glide 4.10 之前的混淆###############
#-keep public class * implements com.bumptech.glide.module.AppGlideModule
#-keep public class * implements com.bumptech.glide.module.LibraryGlideModule
#-keep class com.bumptech.glide.** {
     *; }
#-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
    
#    **[] $VALUES;
#    public *;
#}

# Glide 4.10 及以后
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.module.AppGlideModule
-keep public enum com.bumptech.glide.load.ImageHeaderParser$** {
    
  **[] $VALUES;
  public *;
}

接口功能描述

void applyOptions(@NonNull final Context context, GlideBuilder builder)

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
    
        super.applyOptions(context, builder);
    }

覆写 applyOptions 可以配置 Glide , GlideBuilder 是我们的核心参数

GlideBuilder

GlideBuilder 的 方法

在这里插入图片描述

磁盘缓存设置

  public GlideBuilder setDiskCache(@Nullable DiskCache.Factory diskCacheFactory) {
    
    this.diskCacheFactory = diskCacheFactory;
    return this;
  }

磁盘缓存配置(默认缓存大小250M,默认保存在内部存储中)

设置磁盘缓存保存在外部存储,且指定缓存大小:

builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, diskCacheSize);

设置磁盘缓存保存在自己指定的目录下,且指定缓存大小

builder.setDiskCache(new DiskLruCacheFactory(new DiskLruCacheFactory.CacheDirectoryGetter() {
    
            @Override
            public File getCacheDirectory() {
    
                return diskCacheFolder;
            }
        }, diskCacheSize);

例:


	int IMAGE_CACHE_COUNT = 100 * 1024 * 1024;

    /**
     * 配置图片缓存的路径和缓存空间的大小
     */
    @Override
    public void applyOptions(@NonNull final Context context, GlideBuilder builder) {
    
        builder.setDiskCache(() -> {
    
            File cacheLocation = new File(context.getExternalCacheDir(), "GlideCache");
            if (!cacheLocation.exists()) {
    
                boolean result = cacheLocation.mkdirs();
                AppLogUtils.i(TAG, "create glide image cache dir result == " + result);
            } else {
    
                AppLogUtils.i(TAG, "glide image cache dir is already exists");
            }
            return DiskLruCacheWrapper.create(cacheLocation, Constant.IMAGE_CACHE_COUNT);
        });
    }

内存缓存配置(不建议配置,Glide会自动根据手机配置进行分配)

设置内存缓存大小

builder.setMemoryCache(new LruResourceCache(memoryCacheSize));

设置Bitmap池大小

builder.setBitmapPool(new LruBitmapPool(bitmapPoolSize));

图片质量

Glide默认使用低质量的RGB565,如果想使用高质量

builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888)

void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry)

替换网络请求组件

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
    
        super.registerComponents(context, glide, registry);
    }

Glide 默认使用 HttpURLConnection 做网络请求,在这切换成 Okhttp 请求

registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));

如果要加载HTTPS的图片:

    implementation('com.github.bumptech.glide:glide:4.11.0') {
    
    }
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
    implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'

    /**
     * 注册指定类型的源数据,并指定它的图片加载所使用的 ModelLoader
     */
    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, Registry registry) {
    
        AppLogUtils.i(TAG, "registerComponents");
        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(UnsafeOkHttpClient.getUnsafeOkHttpClient()));
    }
public class UnsafeOkHttpClient {
    

    public static OkHttpClient getUnsafeOkHttpClient() {
    
        try {
    
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
    
                    new X509TrustManager() {
    
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
    
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
    
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    
                            return new java.security.cert.X509Certificate[]{
    };
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
    
                @Override
                public boolean verify(String hostname, SSLSession session) {
    
                    return true;
                }
            });

            builder.connectTimeout(20, TimeUnit.SECONDS);
            builder.readTimeout(20,TimeUnit.SECONDS);

            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
    
            throw new RuntimeException(e);
        }
    }

}

boolean isManifestParsingEnabled()

用于控制是否需要从 Manifest 文件中解析配置文件

注解方式自定义GlideModule为空;或者不为空时,其函数isManifestParsingEnabled()返回true
(一般情况注解方式自定义GlideModule时,isManifestParsingEnabled方法应返回false,防止去继续加载AndroidManifest.xml中的声明,提高性能)

作者:若丶相见
链接:https://juejin.cn/post/6844903938810970120

例:配置AppGlideModule ,来源项目Arms

@GlideModule(glideName = "GlideArms")
public class GlideConfiguration extends AppGlideModule {
    
    public static final int IMAGE_DISK_CACHE_MAX_SIZE = 100 * 1024 * 1024;//图片缓存文件最大值为100Mb

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
    

        LogUtils.debugInfo("GlideConfiguration applyOptions");
        final AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(context);
        builder.setDiskCache(() -> {
    
            // Careful: the external cache directory doesn't enforce permissions
            return DiskLruCacheWrapper.create(DataHelper.makeDirs(new File(appComponent.cacheFile(), "Glide")), IMAGE_DISK_CACHE_MAX_SIZE);
        });

        MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context).build();
        int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
        int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

        int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
        int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);

        builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
        builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));

        //将配置 Glide 的机会转交给 GlideImageLoaderStrategy,如你觉得框架提供的 GlideImageLoaderStrategy
        //并不能满足自己的需求,想自定义 BaseImageLoaderStrategy,那请你最好实现 GlideAppliesOptions
        //因为只有成为 GlideAppliesOptions 的实现类,这里才能调用 applyGlideOptions(),让你具有配置 Glide 的权利
        BaseImageLoaderStrategy loadImgStrategy = appComponent.imageLoader().getLoadImgStrategy();
        if (loadImgStrategy instanceof GlideAppliesOptions) {
    
            ((GlideAppliesOptions) loadImgStrategy).applyGlideOptions(context, builder);
        }
        //回调到 GlideImageLoaderStrategy
    }

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
    
        //Glide 默认使用 HttpURLConnection 做网络请求,在这切换成 Okhttp 请求
        LogUtils.debugInfo("GlideConfiguration registerComponents");
        AppComponent appComponent = ArmsUtils.obtainAppComponentFromContext(context);
        registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(appComponent.okHttpClient()));

        BaseImageLoaderStrategy loadImgStrategy = appComponent.imageLoader().getLoadImgStrategy();
        if (loadImgStrategy instanceof GlideAppliesOptions) {
    
            ((GlideAppliesOptions) loadImgStrategy).registerComponents(context, glide, registry);
        }
    }

    @Override
    public boolean isManifestParsingEnabled() {
    
        return false;
    }
}

使用 AppGlideModule (Generated API)

            GlideApp.with(this)
                    .load(imagePath)
                    .apply(new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC))
                    .into(binding.imageView);

参考地址

Glide Github 地址:https://github.com/bumptech/glide
参考地址:Android 图片加载(四)Glide自定义模块
参考:https://github.com/JessYanCoding/MVPArms

GlideModule AppGlideModule和Generated API详解:https://www.pudn.com/news/62d3e72c864d5c73acbeafb8.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_35691921/article/details/107831312

智能推荐

javascript扩展函数(持续更新)_weixin_34293902的博客-程序员秘密

为什么80%的码农都做不了架构师?&gt;&gt;&gt; ...

玩游戏的你知道早期的貂蝉建模图有多好看吗_游戏建模小能手的博客-程序员秘密

闭月羞花,倾国倾城的女英雄那当之无愧的是貂蝉了,不管是男生还是女生都非常的喜欢她。先不说貂蝉美丽的外表,她在游戏里的伤害力也是很强的。而她的出场率也是很高的,这么想来,貂蝉是有多受欢迎。对于貂蝉的皮肤可能大多数人都喜欢仲夏夜之梦那一款吧,虽然每一款都很好看!(喜欢或者想更多了解游戏建模可以私信主编哦!也可以加企鹅社交团:1046+777+540)但我们这次要说的是貂蝉的原皮肤建模。有句话叫没有对比就没有伤害。在没有可比东西的情况下,我们大家都认为貂蝉的模型很完美。那么现在貂蝉皮肤越来越多,这就让很多

win10下载与安装Apache服务器_win10 http 下载服务器_du_zhaohui的博客-程序员秘密

(一)下载安装首先 去官网下载 Apache服务器,下载地址: http://httpd.apache.org/download.cgi进入之后,选择第一个。选择对应的64位系统。下载完成时是一个压缩包,解压到任意路径,例如 D:\Apache。(二) 修改配置接着 ,修改  Apache的相关配置,打开httpd.conf文件(可以选择

程序员高薪盛宴背后:未来有哪些程序员会被淘汰?_weixin_34272308的博客-程序员秘密

华为35岁辞退事件... 中兴员工坠楼残局... 每次听到这样的新闻,很多程序员一面为不幸的同僚扼腕叹息,一面也在暗暗问自己:技术变化那么快,我会不会被淘汰?又或者程序员十年后还会有今天的收入吗?一面是被淘汰一面是生存收入降低,两顾两相难!假如今天的收入代表比较值钱的话,这个问题其实可以换一种等同的问法,即:● 程序员十年后还会像现在这么值钱吗?十年这里可以一定程度的用未来来代替,那么我们接着对问...

adt项目可以导入as吗 eclipse_请问如何将Eclipse项目导入Android Studio?_朱moyimi的博客-程序员秘密

在较新版本的Android Studio中,引入Eclipse / ADT项目的最佳方法是将其直接导入Android Studio;我们曾建议您首先将它从Eclipse导出到Gradle,但我们还没有经常更新ADT以跟上Android Studio的步伐。无论如何,如果您在启动Android Studio时从“文件”菜单或“欢迎”屏幕中选择“导入项目”,它将引导您完成一个专门的向导,该向导将提示...

PyQt5:QMediaplayer,QVideowidget播放视频(3)_pyqt5 qvideoframe_何其不顾四月天的博客-程序员秘密

PyQt5:QMediaplayer,QVideowidget播放视频(3)简介在 PyQt5:QMediaplayer,QVideowidget播放视频(2)上一篇中完善了界面的布局,快进,慢进。在本篇更新中做了代码做了重构,架构的好坏就另说了,python 没有做过成熟的项目,一直自己写的玩。在本篇中主要更新了UI、播放列表、配置项、媒体文件管理、布局、子控件,还有快进、快退、音量等等一些基础功能。代码结构模块架构文件结构Mode LastWriteTime

随便推点

matlab判断cell为空,问与答1:在VBA代码中如何判断单元格是否为空?_SaeruHikari的博客-程序员秘密

问:如下图所示的工作表,我希望使用VBA代码将空行的背景色设置为灰色,以便于查看(即将上半部分的工作表变为下半部分的样式)。我需要判断某行的单元格为空,然后将该行相应的单元格背景色设置为灰色。如何判断单元格是否为空?答:先看看实现所需效果的代码:Sub setBlankRowColor()Dim lngLastRow As LongDim i As Long'获取工作表中已使用区域最后一行的行号l...

【IOS】深入Objective-C的动态特性(转)_weixin_33978016的博客-程序员秘密

转载至:http://www.onevcat.com/2012/04/objective-c-runtime/Objective-C具有相当多的动态特性,基本的,也是经常被提到和用到的有动态类型(Dynamic typing),动态绑定(Dynamic binding)和动态加载(Dynamic loading)。这些动态特性都是在Cocoa程序开发时非常常用的语言特性,而在这之后,OC在...

vnpy入门操作3——策略模板_csdn vn.py 策略_咸鱼弟的博客-程序员秘密

声明:本文章内容来自于vnpy论坛,平时把自己开始学习的内容记录于此,方便连载!准备编写python语言的工具Visual Studio Code(简称VS Code),由微软推出的编程专用开源编辑器(然后被热心的开源社区加上各种插件打造成了超级IDE)前往VSCode首页,点击Download绿色图标下载后,一路傻瓜安装,运行后看到下述界面:在左侧导航栏顶部的5...

博客搭建(12)-配置vue-element-admin项目接口地址_vueadmin项目地址_end for time的博客-程序员秘密

一.修改.env.development文件二.在vue.config.js中配置proxyproxy: { [process.env.VUE_APP_BASE_API]: { target: process.env.VUE_APP_BASE_API, changeOrigin: true, pathRewrite: { ['^' + process.env.VUE_APP_BASE_API]: ''

linux自旋锁源码,Linux内核源码分析 -- 同步原语 -- 自旋锁 spinlock_St.Helena的博客-程序员秘密

Linux内核源码分析 -- 同步原语 -- 自旋锁 spinlock_ttypedef struct spinlock {union {struct raw_spinlock rlock;#ifdef CONFIG_DEBUG_LOCK_ALLOC# define LOCK_PADSIZE (offsetof(struct raw_spinlock, dep_map))struct {u8 __...

总结一下最短路径的贝尔曼-福特算法(Bellman-Ford)及用队列优化(spfa)_队列优化的bellmanford算法的时间复杂度_zz你的名字的博客-程序员秘密

转发的一二货的:http://blog.csdn.net/riba2534/article/details/54575050 他是从《啊哈算法》上学的,本来想总结一下,一看跟他一模一样,then,,,,,,关于贝尔曼福特算法,假设有n个顶点,我们只需要遍历n-1轮就可以了,因为在一个含n个顶点的图中,任意两点之间的最短路径最多含有n-1条边, 什么原理,我就不讲了,网上大牛博客很多,我在这里上一

推荐文章

热门文章

相关标签