当前位置:网站首页>Glide conclusion
Glide conclusion
2022-07-05 10:16:00 【asahi_ xin】
Custom module
In most cases , Only one line of code is needed to load the image . When we need to change the default configuration , You need to customize the module .
First define your own module class .
public class MyGlideModule implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
}
@Override
public void registerComponents(Context context, Glide glide) {
}
}
stay AndroidManifest.xml Add the following configuration to the file .
<application ...>
<meta-data
android:name="test.nxx.myapplication.MyGlideModule"
android:value="GlideModule" />
</application>
If you want to change Glide Default configuration , In fact, it only needs to be in applyOptions() Method in advance of the method Glide It is OK to initialize the configuration item of .
- setMemoryCache()
Used for configuration Glide Memory cache strategy of , The default configuration is LruResourceCache. - setBitmapPool()
Used for configuration Glide Of Bitmap Buffer pool , The default configuration is LruBitmapPool. - setDiskCache()
Used for configuration Glide Hard disk cache strategy of , The default configuration is InternalCacheDiskCacheFactory. - setDiskCacheService()
Used for configuration Glide An asynchronous actuator that reads images from the cache , The default configuration is FifoPriorityThreadPoolExecutor, That's the first in, first out principle . - setResizeService()
Used for configuration Glide Asynchronous executor that reads non cached images , The default configuration is also FifoPriorityThreadPoolExecutor. - setDecodeFormat()
Used for configuration Glide The decoding mode of loading picture , The default configuration is RGB_565.
Example
public class MyGlideModule implements GlideModule {
public static final int DISK_CACHE_SIZE = 500 * 1024 * 1024;
@Override
public void applyOptions(Context context, GlideBuilder builder) {
// Cache pictures to SD card
builder.setDiskCache(new ExternalCacheDiskCacheFactory(context, DISK_CACHE_SIZE));
// Picture format changed to ARGB_8888
builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
}
@Override
public void registerComponents(Context context, Glide glide) {
}
}
Replace Glide Components
Gilde The network request used is HttpURLConnection, If you want to cache okHttp It needs to be replaced Glide Components .
public class OkHttpStreamFetcher implements DataFetcher<InputStream> {
private final Call.Factory client;
private final GlideUrl url;
private InputStream stream;
private ResponseBody responseBody;
private volatile Call call;
public OkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
this.client = client;
this.url = url;
}
@Override
public InputStream loadData(Priority priority) throws Exception {
Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
String key = headerEntry.getKey();
requestBuilder.addHeader(key, headerEntry.getValue());
}
Request request = requestBuilder.build();
Response response;
call = client.newCall(request);
response = call.execute();
responseBody = response.body();
if (!response.isSuccessful()) {
throw new IOException("Request failed with code: " + response.code());
}
long contentLength = responseBody.contentLength();
stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
return stream;
}
@Override
public void cleanup() {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
// Ignored
}
if (responseBody != null) {
responseBody.close();
}
}
@Override
public String getId() {
return url.getCacheKey();
}
@Override
public void cancel() {
Call local = call;
if (local != null) {
local.cancel();
}
}
}
public class OkHttpUrlLoader implements StreamModelLoader<GlideUrl> {
private final Call.Factory client;
public OkHttpUrlLoader(Call.Factory client) {
this.client = client;
}
@Override
public DataFetcher<InputStream> getResourceFetcher(GlideUrl model, int width, int height) {
return new OkHttpStreamFetcher(client, model);
}
public static class Factory implements ModelLoaderFactory<GlideUrl, InputStream> {
private static volatile Call.Factory internalClient;
private Call.Factory client;
public Factory() {
this(getInternalClient());
}
public Factory(Call.Factory client) {
this.client = client;
}
private static Call.Factory getInternalClient() {
if (internalClient == null) {
synchronized (Factory.class) {
if (internalClient == null) {
internalClient = new OkHttpClient();
}
}
}
return internalClient;
}
@Override
public ModelLoader<GlideUrl, InputStream> build(Context context, GenericLoaderFactory factories) {
return new OkHttpUrlLoader(client);
}
@Override
public void teardown() {
}
}
}
stay MyGlideModule call
public class MyGlideModule implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder builder) {
}
@Override
public void registerComponents(Context context, Glide glide) {
glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory());
}
}
That's it .
Of course Glide The government has provided us with very simple HTTP Component replacement method .
implementation 'com.github.bumptech.glide:okhttp3-integration:1.5.0'
边栏推荐
- Flutter development: a way to solve the problem of blank space on the top of listview
- Generics, generic defects and application scenarios that 90% of people don't understand
- AtCoder Beginner Contest 258「ABCDEFG」
- [tips] get the x-axis and y-axis values of cdfplot function in MATLAB
- Meitu lost 300 million yuan in currency speculation for half a year. Huawei was exposed to expand its enrollment in Russia. Alphago's peers have made another breakthrough in chess. Today, more big new
- .Net之延迟队列
- Interview: how does the list duplicate according to the attributes of the object?
- The king of pirated Dall · e? 50000 images per day, crowded hugging face server, and openai ordered to change its name
- Tianlong Babu TLBB series - questions about skill cooling and the number of attack ranges
- 学习笔记5--高精地图解决方案
猜你喜欢
硬核,你见过机器人玩“密室逃脱”吗?(附代码)
ByteDance Interviewer: how to calculate the memory size occupied by a picture
Comment obtenir le temps STW du GC (collecteur d'ordures)?
Windows uses commands to run kotlin
Unity particle special effects series - the poison spray preform is ready, and the unitypackage package can be used directly - next
Mysql80 service does not start
钉钉、企微、飞书学会赚钱了吗?
Swift set pickerview to white on black background
Swift tableview style (I) system basic
Redis如何实现多可用区?
随机推荐
How to get the STW (pause) time of GC (garbage collector)?
官网给的这个依赖是不是应该为flink-sql-connector-mysql-cdc啊,加了依赖调
《微信小程序-基础篇》小程序中的事件与冒泡
到底谁才是“良心”国产品牌?
AtCoder Beginner Contest 254「E bfs」「F st表维护差分数组gcd」
[C language] the use of dynamic memory development "malloc"
双容水箱液位模糊PID控制系统设计与仿真(Matlab/Simulink)
The Alipay in place function can't be found, and the Alipay in place function is offline
Cent7 Oracle database installation error
TypeError: Cannot read properties of undefined (reading ‘cancelToken‘)
面试:Bitmap像素内存分配在堆内存还是在native中
[NTIRE 2022]Residual Local Feature Network for Efficient Super-Resolution
学习笔记5--高精地图解决方案
Swift set pickerview to white on black background
. Net delay queue
Unity particle special effects series - the poison spray preform is ready, and the unitypackage package is directly used - on
Hard core, have you ever seen robots play "escape from the secret room"? (code attached)
Comparison of batch merge between Oracle and MySQL
小程序中自定义行内左滑按钮,类似于qq和wx消息界面那种
【 conseils 】 obtenir les valeurs des axes X et y de la fonction cdfplot dans MATLAB