写一段在Android app内的html页面里下载pdf文件到本地的代码
时间: 2024-05-06 18:17:23 浏览: 86
Android 下载并打开PDF,Doc,Dwg文档实例
以下是一个简单的在Android app内的html页面里下载pdf文件到本地的代码示例:
在html页面中添加一个下载链接:
```
<a href="pdf/sample.pdf" download>Download PDF</a>
```
在 Android 的 WebView 中启用文件下载:
```java
WebView webView = findViewById(R.id.webView);
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();
}
});
```
这段代码会在 WebView 上设置一个 DownloadListener,当用户点击下载链接时,会启动一个下载任务,并将文件保存到 Android 设备的 Downloads 文件夹中。
阅读全文