I'm using BitmapFactory.decodeStream()
to download images on a background thread.
Here is the code:
URL url = new URL("https://....");
final Bitmap image = BitmapFactory.decodeStream(myUrl.openConnection().getInputStream());
saveImageToExternal("myImage", image, getApplicationContext());
After downloading the image I save it using the function below:
public void saveImageToExternal(String imgName, Bitmap bm, Context context) throws IOException {
File path =new File(getFilesDir(),"ImagesFolder");
File imageFile = new File(path, imgName+".png");
FileOutputStream out = new FileOutputStream(imageFile);
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
MediaScannerConnection.scanFile(context,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
throw new IOException();
}
}
Problem arises if the user interrupts that process by terminating the app or by a sudden internet connection loss. What happens is that some of the images are partially decoded or downloaded.
The following code returns true when checking if the image exits.
File path =new File(getFilesDir(),"ImagesFolder");
File imageFile = new File(path, "myImage.png");
if(imageFile.exists()){
return true;
}
The following images will show how they really appear in an ImageView:
Expected result: Expected result
Real result if interrupted: Real result
Note that both images have the same size.
The question: is there a way to check if the decoding process did finish before the interruption happens or if the image is fully downloaded?