Android - WebViewClient加载页面的速度非常慢

时间:2011-01-06 02:59:25

标签: android browser native webviewclient

作为一名开发人员,我在构建在3G web连接上运行Android webviewclient的应用程序(包含网页)时遇到了非常糟糕的经历。我的一些用户说有些页面最多需要10分钟才能加载。 (我不知道他们是否夸大了,因为他们很沮丧。)就个人而言,我使用HTC Desire运行Android 2.2,并用我自己的手机测试了我的应用程序。实际上,即使对于使用本地存储的网页来发出AJAX请求的应用程序,它在3G上也非常慢。大多数情况下,它只会超时并显示空白页面。当它在WIFI上时,它工作正常并且非常快。

我听过很多人说Android 2.2上的原生浏览器非常快。对我来说,我必须说本机浏览器应用程序在3G上也很慢。有时,Google移动主页甚至无法完成加载。我在新加坡,因此大多数地方的3G覆盖都应该没问题。

是导致问题的设备硬件吗?

1 个答案:

答案 0 :(得分:0)

我不知道与WebView加载时间特别相关的设备特定性能问题。但是,您可能希望同时添加请求超时和网络连接更改侦听器。有关其他信息,您可以按时间请求并报告有关慢速请求的设备和连接信息。

handler = new Handler();
WebView webView = findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient() {
    final long WEBVIEW_REQUEST_TIMEOUT = ...;
    final long WEBVIEW_SLOW_REQUEST_THRESHOLD = ...;
    Runnable onRequestTimeout = null;
    @Override
    public void onPageStarted(WebView view, final String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon); // current impl is no op but be fwd compatible
        saveRequestStartTime();
        onRequestTimeout = new Runnable() {
            @Override
            public void run() {
                handleRequestComplete(url, WebViewClient.ERROR_TIMEOUT);
            }
        };
        handler.postDelayed(onRequestTimeout, WEBVIEW_REQUEST_TIMEOUT);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url); // current impl is no op but be fwd compatible
        handleRequestComplete(url, 0);   // Return 0 onSuccess. All WebViewClient defined errors < 0. 
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl); // current impl is no op but be fwd compatible
        handleRequestComplete(failingUrl, errorCode);
    }

    private void handleRequestComplete(String url, int errorCode) {
        if (onRequestTimeout != null) {
            handler.removeCallbacks(onRequestTimeout);
        }
        onRequestTimeout = null;
        final long elapsedTime = getRequestElapsedTime();
        if (elapsedTime > WEBVIEW_SLOW_REQUEST_THRESHOLD) {
            reportSlowRequest(elapsedTime, url, errorCode);
        }
        clearRequestTime();
    }

    private void saveRequestStartTime() {...}
    private long getRequestElapsedTime() {...}
    private void clearRequestTime() {...}
    private void reportSlowRequest(long elapsedTime, String url, int errorCode) {...}
});