I am trying to download file from url and save it to general downloads folder. setDestinationInExternalPublicDir()
doesn't work and doesn't throw any exception. But setDestinationInExternalFilesDir()
works fine. Any idea what the reason can be ?
My code is like this:
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
if (url.startsWith("data:")) {
save(url);
return;
}
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.setDescription(getResources().getString(R.string.downloadingMsg));
String filename = URLUtil.guessFileName(url, contentDisposition, mimeType);
request.setTitle(filename);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//DOESN'T WORK
request.setDestinationInExternalPublicDir("Downloads", filename);
//WORKS
//request.setDestinationInExternalFilesDir(getApplicationContext(), "Downloads", filename);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), R.string.downloadingMsg, Toast.LENGTH_LONG).show();
}
});
And manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
So, i finally could get the setDestinationInExternalPublicDir() function work. Thanks to CommonsWare. By following Commonsware's comment and answer here I learnt that on android versions 6+, even though permissions declared in manifest file, they should still be requested on runtime as well. And guess what, i was working with android 7... That is way, i was getting permission denied error.
So i added these lines on my onCreate()
function which will prompt users for the permission on runtime as well (which solved my problem finally):
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int PERMISSION_REQUEST_CODE = 1;
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
}
}