为我写一个WebView下载图片的代码
时间: 2024-06-10 12:07:31 浏览: 75
当然可以,下面是一个简单的WebView下载图片的代码:
WebView webView = new WebView(context);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
// 加载完成后,开始查找图片并下载
view.loadUrl("javascript:(function(){" +
"var imgs = document.getElementsByTagName('img');" +
"for(var i=0;i<imgs.length;i++){" +
"var img = imgs[i];" +
"var url = img.src;" +
"window.location.href = 'download:' + url;" +
"}" +
"})()");
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// 拦截下载链接,进行下载操作
if(url.startsWith("download:")) {
String downloadUrl = url.substring("download:".length());
startDownload(downloadUrl); // 启动下载
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.loadUrl("https://www.example.com"); // 加载网页
阅读全文