当前位置:网站首页>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'
边栏推荐
- Swift saves an array of class objects with userdefaults and nssecurecoding
- Constraintlayout officially provides rounded imagefilterview
- 如何获取GC(垃圾回收器)的STW(暂停)时间?
- Six simple cases of QT
- TypeError: Cannot read properties of undefined (reading ‘cancelToken‘)
- Tianlong Babu TLBB series - single skill group injury
- 【 conseils 】 obtenir les valeurs des axes X et y de la fonction cdfplot dans MATLAB
- isEmpty 和 isBlank 的用法区别
- ArcGIS Pro 创建要素
- Have you learned to make money in Dingding, enterprise micro and Feishu?
猜你喜欢

isEmpty 和 isBlank 的用法区别

【系统设计】指标监控和告警系统

The most complete is an I2C summary

把欧拉的创新带向世界 SUSE 要做那个引路人

Redis如何实现多可用区?

QT event filter simple case
![[C language] the use of dynamic memory development](/img/b7/3337bf0df9232d3a44eaeb46b39c63.png)
[C language] the use of dynamic memory development "malloc"

能源势动:电力行业的碳中和该如何实现?

Those who are good at using soldiers, hide in the invisible, and explain the best promotional value works in depth in 90 minutes

Pagoda panel MySQL cannot be started
随机推荐
Cut off 20% of Imagenet data volume, and the performance of the model will not decline! Meta Stanford et al. Proposed a new method, using knowledge distillation to slim down the data set
[论文阅读] KGAT: Knowledge Graph Attention Network for Recommendation
. Net delay queue
Z-blog template installation and use tutorial
到底谁才是“良心”国产品牌?
Apache dolphin scheduler system architecture design
QT realizes signal transmission and reception between two windows
ArcGIS Pro creating features
Swift set pickerview to white on black background
如何写出高质量的代码?
Kotlin compose multiple item scrolling
What is the origin of the domain knowledge network that drives the new idea of manufacturing industry upgrading?
Livedata interview question bank and answers -- 7 consecutive questions in livedata interview~
驱动制造业产业升级新思路的领域知识网络,什么来头?
Zblogphp breadcrumb navigation code
La vue latérale du cycle affiche cinq demi - écrans en dessous de cinq distributions moyennes
面试:List 如何根据对象的属性去重?
LiveData 面试题库、解答---LiveData 面试 7 连问~
To bring Euler's innovation to the world, SUSE should be the guide
Energy momentum: how to achieve carbon neutralization in the power industry?