乐闻世界logo
搜索文章和话题

How to download files from webview Android?

1个答案

1

In Android, to download files from WebView, you need to follow several steps to ensure WebView has the necessary permissions and capabilities for file downloads. Here are the steps to implement this functionality:

1. Request Storage Permissions: First, ensure your application has the required permissions to write to storage. Request these permissions at runtime, typically in onCreate or before the user initiates a download.

java
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE); }

Where MY_PERMISSIONS_REQUEST_WRITE_STORAGE is an integer constant used to identify the permission request in callback methods.

2. Set WebView's DownloadListener: Next, configure WebView's DownloadListener to capture the download event when the user clicks a link.

java
webView.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); String cookies = CookieManager.getInstance().getCookie(url); request.addRequestHeader("cookie", cookies); 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(); } });

Here, when the download initiates, DownloadManager processes the actual file download. We set required headers, description, title, and destination directory.

3. Handle Permission Request Callback: Manage the user's response to runtime permission requests. If permission is granted, proceed with the download process.

java
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_WRITE_STORAGE: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission granted; proceed with storage-related tasks } else { // permission denied; disable dependent functionality } return; } // other 'case' lines for additional permissions } }

4. Ensure Internet Permissions: Declare the INTERNET permission in your AndroidManifest.xml file, as file downloads require network access.

xml
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

5. Consider FileProvider: If your app targets API level 24 (Android 7.0) or higher and you implement custom file downloads instead of DownloadManager, use FileProvider when handling file URIs to avoid FileUriExposedException.

6. Handle Special Cases for Different Android Versions: Depending on the Android version, address platform-specific requirements, such as adapting to Scoped Storage.

By following these steps, your application should successfully download files from WebView. Remember to prioritize user experience in practice, including displaying download progress and implementing error handling.

2024年6月29日 12:07 回复

你的答案