要实现Webview下载其他格式的文件,需要设置Webview的DownloadListener,同时在Manifest文件中添加写入存储权限。
以下是示例代码:
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.web_view);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
// 设置DownloadListener
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
// 下载文件
downloadFile(url, contentDisposition, mimetype);
}
});
webView.loadUrl("http://example.com/file.pdf");
}
// 下载文件
private void downloadFile(String url, String contentDisposition, String mimetype) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(contentDisposition);
request.setMimeType(mimetype);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.pdf");
// 获取DownloadManager
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
}
}