How to Download Any Type of Files in WebView Android Studio?
If your website has a download option you really need to enable it from your Android WebView app. The Android java code below can be used to download any type of file to your Android device’s storage with the file’s original name, be it a .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.
Download Manager
Download Any Type of Files in WebView Android Studio?
in MainActivity.java
myWebView.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.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(); } });
And also remember that you need to set the write to external storage permission in the manifest. If not above code will not work.
in AndroidMainfest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And also we must request user permission for devices. In the next article, We will tell you How to request user permission for devices in Android Studio?
Read also:
- How to create Splash Screen? Add Welcome Screen to Your App?
- How to Improve WebView Performance Android Studio?
- How to open other links in external browser or app – WebView App?