Search code examples
androidandroid-fileandroid-download-manager

Downloaded image showing in android studio but not gallery


I am trying to download an image using a url through a service I've created and when I inspect my device's file directory through Android Studio debugger, I can see the file in the device:

The red file is the downloaded file in question. The green image file is a file I manually dragged in to the directory through Windows Explorer.

enter image description here

I can successfully see and open the green file in my Gallery app but the red file (and all the other files listed in that directory) are no where to be found. I cannot see them in Windows Explorer either. Am I supposed to identify them as images somewhere in my code so that the file system knows it's an image?

This is the part where I download the image:

Request.Builder builder = new Request.Builder();
builder = builder.url(downloadFileUrl);
builder = builder.addHeader("RANGE", "bytes=" + existLocalFileLength);
Request request = builder.build();

Call call = okHttpClient.newCall(request);
Response response = call.execute();

if (response != null && response.isSuccessful()) {
 RandomAccessFile downloadFile = new RandomAccessFile(existLocalFile, "rw");
 downloadFile.seek(existLocalFileLength);

 ResponseBody responseBody = response.body();
 InputStream inputStream = responseBody.byteStream();
 BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
 byte data[] = new byte[102400];

 long totalReadLength = 0;

 int readLength = bufferedInputStream.read(data);

 while (readLength != -1) {

  if (getDownloadManager().isDownloadPaused()) {
   ret = DOWNLOAD_PAUSED;
   break;
  } else if (getDownloadManager().isDownloadCanceled()) {
   ret = DOWNLOAD_CANCELED;
   break;
  } else {

   downloadFile.write(data, 0, readLength);

   totalReadLength = totalReadLength + readLength;

   int downloadProgress = (int)((totalReadLength + existLocalFileLength) * 100 / downloadFileLength);

   getDownloadManager().updateTaskProgress(downloadProgress);

   readLength = bufferedInputStream.read(data);
  }
 }
}

Solution

  • You need to scan the saved file using MediaScannerConnection:

    private void scanFile(String path) {
    
        MediaScannerConnection.scanFile(context,
                new String[] { path }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
    
                    public void onScanCompleted(String path, Uri uri) {
                        Log.d("Tag", "Scan finished. You can view the image in the gallery now.");
                    }
                });
    }
    

    Call this on your existLocalFile's path:

    scanFile(existLocalFile.getAbsolutePath());