Glide 加载网络图片

GitHub 地址

1、权限

  1. <uses-permission android:name="android.permission.INTERNET" />
  2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2、添加依赖

  1. implementation 'com.github.bumptech.glide:glide:4.8.0'

3、加载网络图片

  1. Glide.with(v).load(picUrl).placeholder(R.mipmap.ic_loading).error(R.mipmap.ic_load_failure).into(ivPic);

4、图片缓存

  1. //禁止缓存
  2. Glide.with(this).load(imageUrl).skipMemoryCache(true).into(imageView);
  3. //清除缓存,必须在UI线程中调用
  4. Glide.get(context).clearMemory();
  1. //设置缓存
  2. Glide.with(this).load(imageUrl).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
  3. DiskCacheStrategy.ALL:缓存源资源和转换后的资源
  4. DiskCacheStrategy.NONE:不作任何磁盘缓存
  5. DiskCacheStrategy.SOURCE:缓存源资源
  6. DiskCacheStrategy.RESULT:缓存转换后的资源

5、Cookies 设置

保存cookies

  1. public class SaveCookiesInterceptor implements Interceptor {
  2. @Override
  3. public Response intercept(Chain chain) throws IOException {
  4. Response originalResponse = chain.proceed(chain.request());
  5. if (!originalResponse.headers("Set-Cookie").isEmpty()) {
  6. HashSet<String> cookies = new HashSet<>();
  7. for (String header : originalResponse.headers("Set-Cookie")) {
  8. cookies.add(header);
  9. }
  10. UserKeeper.setCookies(cookies);
  11. }
  12. return originalResponse;
  13. }
  14. }

设置 Cookies

  1. HashSet<String> preferences = UserKeeper.getCookies();
  2. LazyHeaders.Builder builder = new LazyHeaders.Builder();
  3. for (String cookie : preferences) {
  4. builder.addHeader("Cookie", cookie);
  5. }
  6. GlideUrl cookie = new GlideUrl(url, builder.build());
  7. Glide.with(context).load(cookie).apply(options).into(view);

6、Gilde 设置 Tag 报错问题

  1. //清单文件中加入
  2. <application
  3. android:name=".MyApplication"
  4. ......>
  5. </application>
  1. public class MyApplication extends Application {
  2. @Override public void onCreate() {
  3. super.onCreate();
  4. ViewTarget.setTagId(R.id.glide_tag);
  5. }
  6. }
  1. //创建资源文件:src/main/values/ids.xml
  2. <resources>
  3. <item type="id" name="glide_tag" />
  4. </resources>

7、混淆设置

  1. ##Glide
  2. -dontwarn com.bumptech.glide.**
  3. -keep class com.bumptech.glide.**{*;}
  4. -keep public class * implements com.bumptech.glide.module.GlideModule
  5. -keep public class * extends com.bumptech.glide.AppGlideModule
  6. -keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  7. **[] $VALUES;
  8. public *;
  9. }