【问题标题】:android webview measure times of all resourcesandroid webview测量所有资源的时间
【发布时间】:2015-09-13 08:18:21
【问题描述】:

可以测量一个webview的所有资源的加载时间吗? 例如,为了加载完整的网络,我使用:

public void onPageStarted(WebView view, String url, Bitmap favicon) {
    startingTime = System.currentTimeMillis();
    super.onPageStarted(view, url, favicon);
}

public void onPageFinished(WebView view, String url) {
    timeElapsed = System.currentTimeMillis() - startingTime;               
    super.onPageFinished(view, url);
}

但为了测量 CSS、图像等的负载。我使用

public HashMap<String, Long> resources = new HashMap<String, Long>();

public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request){
        resources.put(request.getUrl().toString(), System.currentTimeMillis()); 
        WebResourceResponse response =  super.shouldInterceptRequest(view, request);
        return response;
}

public void onLoadResource(WebView view, String url) {
        if(resources.containsKey(url)){
            Long timeStartResource = resources.get(url);
            Long timeElapseResource = System.currentTimeMillis() - timeStartResource;
        }
        super.onLoadResource(view, url);
}

我认为onLoadResource方法是在加载资源时执行的,但根据文档

public void onLoadResource(WebView 视图,字符串 url)。
通知宿主应用程序 WebView 将加载给定 url 指定的资源。

还有

public WebResourceResponse shouldInterceptRequest(WebView 视图,WebResourceRequest 请求)
将资源请求通知宿主应用程序并允许应用程序返回数据。如果返回值为 null,WebView 将照常继续加载资源。否则,将使用返回响应和数据。

它们都在加载资源之前运行。有什么方法可以测量这些时间吗?

【问题讨论】:

    标签: android time webview android-webview


    【解决方案1】:

    有一个很棒的 HTML5 API 可供您的页面访问。见http://www.sitepoint.com/introduction-resource-timing-api/

    从 KitKat 开始,WebView 基于 Chromium,它支持这个 API。要检查这一点,请为您的应用打开 remote web debugging(假设您已为 WebView 启用 JavaScript),然后尝试在控制台中进行评估:

    window.performance.getEntriesByType('resource')
    

    对于页面已加载的每个资源,您将获得一个 PerformanceResourceTiming 对象数组。

    为了将您的信息传输到 Java 端,您可以使用注入的 Java 对象。

    【讨论】:

      【解决方案2】:

      您可以使用 onPageFinished() 完成此问题的答案,description here.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-05
        • 2011-06-18
        • 1970-01-01
        • 2023-03-13
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多