Asynchronously load resources in Android Webview

        WebViewClient.shouldInterceptRequest is executed in the UI thread. If resource loading is blocked, it will be blocked during display, so external resources need to be loaded asynchronously.

        All the searches on the Internet are implemented with PipeInputStream/PipeOutputStream. After testing, it is found that when this method outputs content, PipeInputStream has been closed. So it was changed to overload InputStream implementation, and the test passed.

        The following example uses http to access remote resources, where http is implemented using OkHttp, which is not difficult, so this part of the code is not posted:

 public static class UrlInputStream extends InputStream {
        private final String url;
        private final Map<String, String> headers;

        private byte[] stream = null;
        private int i = 0;
        private int len = 0;

        public UrlInputStream(String url, Map<String, String> headers) {
            this.url = url;
            this.headers = headers;
        }

        @Override
        public int read() throws IOException {
            if (stream == null) { //stream初始化必须放在read中,放在构造函数中,就会阻塞调用线程
                Request req = http.buildGet(url, headers,null, null);
                try (Response resp = http.syncSend(req);
                     ResponseBody body = resp.body()){
                    stream = body.bytes();
                    len = stream.length;
                    LOG.debug("read {}, len:{}", url, len);
                } catch (IOException e) {
                    LOG.error("Fail to get {}", url, e);
                }
            }

            if (i >= len) {
                return -1;
            }
            return (((int)stream[i++]) & 0xff); //此处小心,必须强转后去除高位,否则可能会返回负数
        }
    }

Use UrlInputStream in WebViewClient.shouldInterceptRequest:

InputStream in = new HttpClient.UrlInputStream(url, null);
return new WebResourceResponse(mimeType, DEFAULT_CHARSET_NAME, in);

Guess you like

Origin blog.csdn.net/flyinmind/article/details/128031455