Search code examples
javaandroidandroid-download-manager

How to set download directory in DownloadManager?


I am using DownloadManager but it puts the download somewhere I don't know. I want to download the file in a specific folder like "mp3" in sdcard.

Here is the code I am using :

private class HelloWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView webview, String url)
    {
        if(url.endsWith(".mp3") || !url.startsWith("http://xnm")) {
            String servicestring = Context.DOWNLOAD_SERVICE;
            DownloadManager downloadmanager;
            downloadmanager = (DownloadManager) getSystemService(servicestring);
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new Request(uri);
            Long reference = downloadmanager.enqueue(request);

            setProgressBarIndeterminateVisibility(false);
         }
         else {
             mWebView.loadUrl(url);
             setProgressBarIndeterminateVisibility(true);
         }

        return true;
    }
    @Override
    public void onPageFinished(WebView webview, String url){
        super.onPageFinished(webview, url);
        setProgressBarIndeterminateVisibility(false);
     }

}

Thanks in advance !!


Solution

  • Actually I got it working after searching a lot and here it is the code to add in existing.

    File folder = new File(Environment.getExternalStorageDirectory() + "/any");
                if (!folder.exists()) {
                    folder.mkdir();
                }
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDestinationInExternalPublicDir("/Download/Global Mp3", nameOfFile);
    

    And we need this permission in manifest file

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    Thats it !!! Maybe it will help someone else