Download Any Type of Files in Webview Android Studio Java

Download all types of files in android webview

The Android java code below can be used to download any type of files to your Android device’s storage with the file’s original name, be it an .mp3, mp4,jpg or pdf, the code will download any file that is downloadable

This code is for Android webview, just paste it below in the oncreate method of webview activity

Remember that you need set the write to external storage permission in the manifest.

and must request user permission for devices starting android Marshmallow.

 

Here is the android java code to download all types of files from Webview

 

wv.setDownloadListener(new DownloadListener() {     @Override     public void onDownloadStart(String url, String userAgent, String      contentDisposition , String mimeType, long contentLength) {         DownloadManager.Request request = new      DownloadManager.Request(Uri.parse(url));
request
.setMimeType(mimeType);
//------------------------COOKIE!!------------------------
String cookies = CookieManager.getInstance().getCookie(url);
request
.addRequestHeader("cookie", cookies);
//------------------------COOKIE!!------------------------
request
.addRequestHeader("User-Agent", userAgent);
request
.setDescription("Downloading file...");
request
.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request
.allowScanningByMediaScanner();
request
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm
.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
}
});

 

, ,

Post navigation

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.