I want to cache images displayed in WebView for a certain time, for example. 7 days, so I needed to both save image caches to disk, and load them from disk and provide them to WebView.
Also I needed to resize images to avoid WebView; Crash on High Memory Usage, so I implemented the caching and resizing logic in the lock function called " fetchBitmap ".
As stated in the Android documentation, " shouldInterceptRequest " works in a thread other than the user interface thread, so I can perform network functions in this function, but as I see it, the blocking call causes the WebView to freeze.
The way the function works makes me use a lock call , and I cannot pass Runnable, for example. for future completion.
Any workarounds?
webView.setWebViewClient(new WebViewClient() {
private boolean isImage(String url) {
if (url.contains(".jpg") || url.contains(".jpeg")
|| url.contains(".png")) {
return true;
}
return false;
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (isImage(url)) {
Bitmap bitmap = ImageUtil.fetchBitmap(url);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
return new WebResourceResponse("image/*", "base64", bs);
}
return null;
}
});
- UPDATE -
OK, I changed the logic, now I just block reading from disk and process the network load (caching) separately in runnable; " fetchBitmapForWebView "; it doubles the load on the network when the cache is unavailable, but the user interface is now more responsive.
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (isImage(url)) {
Bitmap bitmap = ImageUtil.fetchBitmapForWebView(url);
if (bitmap == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
return new WebResourceResponse("image/*", "base64", bs);
}
return null;
}