gpt4 book ai didi

android - WebViewClient shouldInterceptRequest 卡住 WebView

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:14 25 4
gpt4 key购买 nike

我想在特定时间缓存 WebView 中显示的图像,例如7 天,所以我需要将图像缓存保存到磁盘并从磁盘加载它们并将它们提供给 WebView。

我还需要调整图像的大小以避免 WebView;内存使用率高时崩溃,因此我在名为“fetchBitmap”的阻塞函数中实现了缓存调整大小逻辑。

正如 Android 文档所述,“shouldInterceptRequest”在 UI 线程以外的线程上运行,因此我可以在此函数中进行联网,但正如我所见,阻塞调用会导致要卡住的 WebView。

该函数的行为方式迫使我使用阻塞 调用,并且我不能为例如以备将来完成。

有什么解决方法吗?

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;
}
});

--更新--

OK,我改变了逻辑,现在我只是从磁盘 block 读取,并在一个runnable中单独处理网络负载(缓存); "fetchBitmapForWebView";当缓存不可用时,它会使网络负载加倍,但 UI 现在的响应速度更快。

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;
}

最佳答案

一般原则是你不应该在 shouldInterceptRequest 中做任何繁重的处理,因为它是一个同步调用(尽管是在另一个线程上)。所有网络请求的调用都在同一个线程上处理,因此阻塞一个请求将导致所有其他请求也被阻塞。

对于您的用例,我会考虑在您的应用程序中运行一个小型网络服务器,它将执行所有必需的缓存和处理。当然,您还需要重写显示的网页中的所有链接,以便指向本地服务器而不是原始 Web 服务器,因此在某些情况下可能会很麻烦。但作为一种通用方法,这将极大地有助于卸载繁重的工作并维护本地缓存。

周围有许多简单的 Java Web 服务器,例如:

关于android - WebViewClient shouldInterceptRequest 卡住 WebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com