Last active
July 24, 2020 16:46
-
-
Save yushaojian13/7b623f1a6d971889236c to your computer and use it in GitHub Desktop.
A task to download and save image to SD card with Glide
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What a lovely piece of code. I would like to ask 2 things: