Implementation of Android Cache Large Graph to SD Card

  • 2021-12-19 06:50:20
  • OfStack

This article example for everyone to share the implementation of Android cache map to SD card specific code, for your reference, the specific content is as follows

This function mainly aims at the fact that the resource picture is too large and occupies the volume of apk, so download the picture in advance, take it locally when loading through Glide, apply it directly when the value is successful, and save time. If the local picture does not exist or the value fails, it will be loaded through the network. . .

1. Open child threads
2. Cache locally through the picture url
3. Judge whether SD is mounted or not
4. Judge whether the file exists locally
5. Existence puts the file under the specified path


public void downloadOnly(@Nullable final List<String> imageUrlList) {
 
    if (Tools.isEmpty(imageUrlList)) {
      return;
    }
 
    if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
      return;
    }
 
    new Thread(new Runnable() {
      @Override
      public void run() {
        final File parent = MainApplication.getContext().getExternalCacheDir();
        for (String url : imageUrlList) {
          try {
            File tempFile = findImageByUrl(url, Tools.getApplication());
            if (tempFile == null) {
              File file = Glide
                  .with(MainApplication.getContext())
                  .load(url)
                  .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                  .get();
              Uri uri = Uri.parse(url);
              String fileName = uri.getLastPathSegment();
              if (Tools.notEmpty(fileName)) {
                copy(file, new File(parent, uri.getLastPathSegment()));
              }
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }).start();
  }
 
  // Copy a file 
  public void copy(File source, File target) {
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
      fileInputStream = new FileInputStream(source);
      fileOutputStream = new FileOutputStream(target);
      byte[] buffer = new byte[1024];
      while (fileInputStream.read(buffer) > 0) {
        fileOutputStream.write(buffer);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (fileInputStream != null) {
          fileInputStream.close();
        }
 
        if (fileOutputStream != null) {
          fileOutputStream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

1. Judge whether SD is mounted or not
2. Judge whether the file URL is empty
3. Judge whether the file exists or not


// Find if a local file exists 
  @Nullable
  public static File findImageByUrl(@Nullable String url, @Nullable Context context) {
    if (Tools.isEmpty(url) || context == null) {
      return null;
    }
    try {
      if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        return null;
      }
      Uri uri = Uri.parse(url);
      String fileName = uri.getLastPathSegment();
      if (Tools.notEmpty(fileName)) {
        File file = new File(context.getExternalCacheDir(), fileName);
        return file.exists() ? file : null;
      }
    } catch (Exception e) {
      return null;
    }
    return null;
  }

After the above process operation, the stable network has downloaded the file to the local, just call the method to load, if the network is unstable without successful download is fine, glide will assist in loading! ! !


 /**
   *  Load pictures 
   *  First from the cache according to url Determine whether there is a picture according to the name 
   */
  public static void loadImageByCacheFirst(Context context, String url, ImageView imageView) {
    try {
      if (context == null) {
        return;
      }
 
      File file = findImageByUrl(url, context);
      if (file != null) {
        Glide.with(context).load(file).into(imageView);
      } else {
        Glide.with(context).load(url).into(imageView);
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }

Related articles: