不用遍历方式,能否从webview加载过程中拦截已经打开的图片缓存地址
时间: 2024-02-26 08:57:52 浏览: 25
可以通过WebViewClient的`shouldInterceptRequest()`方法在WebView加载网页过程中拦截已经打开的图片缓存地址。具体步骤如下:
1. 在WebViewClient的`shouldInterceptRequest()`方法中判断请求是否是图片类型:
```
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (request.getUrl().toString().endsWith(".jpg")
|| request.getUrl().toString().endsWith(".jpeg")
|| request.getUrl().toString().endsWith(".png")
|| request.getUrl().toString().endsWith(".gif")) {
// 是图片类型,拦截请求
// ...
}
return super.shouldInterceptRequest(view, request);
}
```
2. 如果请求是图片类型,就可以从缓存中获取图片数据:
```
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Android 5.0及以上版本
WebResourceResponse response = view.getWebView().getCacheMode() == WebSettings.LOAD_CACHE_ONLY
? null : view.getWebView().getCacheResponse(request);
if (response != null) {
// 获取缓存中的图片数据
InputStream inputStream = response.getData();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// 处理图片
// ...
// 返回缓存中的图片数据
return response;
}
} else {
// Android 4.4及以下版本
String url = request.getUrl().toString();
File cacheFile = webView.getWebView().getCacheDir().getAbsoluteFile();
File file = new File(cacheFile, url);
if (file.exists()) {
// 获取缓存中的图片数据
FileInputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// 处理图片
// ...
// 返回缓存中的图片数据
return new WebResourceResponse("image/*", "", inputStream);
}
}
```
需要注意的是,从缓存中获取的图片可能不是最新的,建议在需要时再通过网络获取最新的图片。另外,从缓存中获取图片数据可能会阻塞UI线程,建议在子线程中执行。