Search code examples
androidandroid-studioandroid-download-manager

How do i download files to the local downloads folder?


I enabled the download settings for files with WebView. I'm saving files with DownloadManager. But the files do not appear in the local downloads directory. The files I've downloaded are save here.

> file/storage/emulated/0/Android/data/com.myapp/files/x.mp3

I've tried a lot. But somehow it was not downloaded in the local downloads folder. What should I do?

My Code

String string = String.valueOf((URLUtil.guessFileName(url, contentDisposition, mimeType)));

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setMimeType(mimeType);
            String cookies = CookieManager.getInstance().getCookie(url);

            request.addRequestHeader("cookie", cookies);
            request.addRequestHeader("User-Agent", userAgent);
            request.setTitle("test17");
            request.setDescription("Downloading file...");
            request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
            request.allowScanningByMediaScanner();

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS ,  string);
            DownloadManager dm = (DownloadManager)getActivity().getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);

Solution

  • According to documentation there are 2 types of external storage

    • Public files: Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user. For example, photos captured by your app or other downloaded files should be saved as public files.
    • Private files: Files that rightfully belong to your app and will be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they don't provide value to the user outside of your app.

    In your code, calling DownloadManager.Request.setDestinationInExternalFilesDir() is equivalent to calling Context.getExternalFilesDir() which will get private file directory.

    If you want to save downloaded files to Download directory, use DownloadManager.Request.setDestinationInExternalPublicDir()

    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "x.mp3");
    // call allowScanningByMediaScanner() to allow media scanner to discover your file
    request.allowScanningByMediaScanner();