-
-
Save engmms/cf2eade9c8171e4d2d7a8cb9353ef0af to your computer and use it in GitHub Desktop.
Android WebView File Download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment