Skip to content

Instantly share code, notes, and snippets.

@wangsy
Last active April 2, 2021 07:54
Show Gist options
  • Save wangsy/417e39ea24250958977c9538579c1d3e to your computer and use it in GitHub Desktop.
Save wangsy/417e39ea24250958977c9538579c1d3e to your computer and use it in GitHub Desktop.
Android WebView File Download
mWebContents.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file");
String fileName = contentDisposition.replace("inline; filename=", "");
fileName = fileName.replaceAll(".+UTF-8''", "");
fileName = fileName.replaceAll("\"", "");
fileName = URLDecoder.decode(fileName, "UTF-8");
request.setTitle(fileName);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
} catch (Exception e) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(getBaseContext(), "첨부파일 다운로드를 위해\n동의가 필요합니다.", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
110);
} else {
Toast.makeText(getBaseContext(), "첨부파일 다운로드를 위해\n동의가 필요합니다.", Toast.LENGTH_LONG).show();
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
110);
}
}
}
}
@inimatic
Copy link

Add }) in the end

@abdesamad12
Copy link

Thank you so much, Boss. you the best. I am really appreciating your work ☺️

@dayanidhicse
Copy link

But this is not working for POST request made and response will be file. can you add that use case also.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment