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

如何从安卓 webview 中下载文件?

4 个月前提问
3 个月前修改
浏览次数47

1个答案

1

在Android中,要从WebView中下载文件,您需要做几个步骤来确保WebView具有下载文件的权限和功能。以下是实现此功能的步骤:

  1. 请求存储权限: 首先,您需要确保应用程序具有写入存储的权限。在运行时请求必要的权限,这通常在onCreate或在用户开始下载之前完成。

    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); }

    其中MY_PERMISSIONS_REQUEST_WRITE_STORAGE是一个整数常量,用于在权限回调中识别请求。

  2. 设置WebView的DownloadListener: 接下来,设置WebView的DownloadListener,以便在用户点击链接进行下载时能够捕获这个事件。

    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(); } });

    这里,当下载开始时,我们使用DownloadManager来处理实际的文件下载。我们为下载请求设置了必要的头信息、描述、标题和目标目录等。

  3. 处理权限请求的回调: 处理用户对运行时权限请求的响应。如果用户授予权限,则可以继续下载过程。

    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 was granted, yay! Do the // storage-related task you need to do. } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; } // other 'case' lines to check for other // permissions this app might request. } }
  4. 确保Internet权限: 在您的AndroidManifest.xml文件中声明INTERNET权限,因为下载文件需要网络访问。

    xml
    <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  5. 考虑FileProvider: 如果您的应用目标API级别是24(Android 7.0)或更高,并且您决定使用自己的代码下载文件而不是DownloadManager,请记住在处理文件URI时使用FileProvider,以避免FileUriExposedException

  6. 处理不同Android版本的特殊情况: 根据不同的Android版本,可能需要处理特殊情况,例如适配Scoped Storage。

通过这些步骤,您的应用应该能够成功地从WebView下载文件。记得在实际使用时考虑用户体验,比如下载进度的显示,以及错误处理等。

2024年6月29日 12:07 回复

你的答案