Skip to content

Instantly share code, notes, and snippets.

@yushaojian13
Last active July 24, 2020 16:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save yushaojian13/7b623f1a6d971889236c to your computer and use it in GitHub Desktop.
Save yushaojian13/7b623f1a6d971889236c to your computer and use it in GitHub Desktop.
A task to download and save image to SD card with Glide
public class ImageSaveTask extends AsyncTask<String, Void, Void> {
private Context context;
public ImageSaveTask(Context context) {
this.context = context;
}
@Override
protected Void doInBackground(String... params) {
if (params == null || params.length < 2) {
throw new IllegalArgumentException("You should offer 2 params, the first for the image source url, and the other for the destination file save path");
}
String src = params[0];
String dst = params[1];
try {
File file = Glide.with(context)
.load(src)
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
File dstFile = new File(dst);
if (!dstFile.exists()) {
boolean success = dstFile.createNewFile();
if (!success) {
return null;
}
}
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(new FileOutputStream(dst));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (InterruptedException | ExecutionException | IOException e) {
e.printStackTrace();
}
return null;
}
}
@davidsvarrer
Copy link

What a lovely piece of code. I would like to ask 2 things:

  1. How do I use this code to load images into the ANdroid file system? It is an AsyncTask, but I tried some methods to run it in the background which I could not make work.
  2. Can this run in the foreground instead? I am a bit green on Android task system 👍
  3. In case we can use it, how do we remunerate you for this code snippet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment