Can you measure the time it takes to load a web page in a webView in Android?

余生颓废 提交于 2019-12-11 02:49:42

问题


There are lots of questions regarding the WebView in Android taking too long to load, however I'd like to be able to time exactly how long it takes to completely load, and then display the result.

Is this possible? I could start a timer but does the WebView have an HTML OnLoad style call once it has loaded?

The code I have is basic:

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.pageloadtest);

        webView = (WebView) findViewById(R.id.webView1);
        webView.loadUrl("http://www.airometricwireless.com");
}

This loads the page fine. I just need to time how long it takes.


回答1:


Probably not scientifically accurately, but I guess you could call

long a, b;

mWebView.setWebViewClient(new WebViewClient() {

    public void onPageStarted(WebView view, String url) {
        a = (new Date()).getTime;
    }

    public void onPageFinished(WebView view, String url) {
        b = (new Date()).getTime;
    }
});

Then b - a.

Hope it helps.

Best regards.




回答2:


You can use onPageFinished but as the docs say, "When onPageFinished() is called, the rendering picture may not be updated yet."

Also it's only meaningful for simple pages as it won't factor in IFRAMEs or dynamically-loaded content e.g. JavaScript that loads other JavaScript such as social media buttons, adverts, tracking scripts etc. And it's typically that stuff that causes pages to feel unperformant.

What people often mean when they say "it's slow to load" is "it takes a long time before I can interact with the page" which is very different from how long it takes to load the assets. For this you probably want to test when an onDOMReady-like event fires from JavaScript, or if not using that, when non-deferred JS actually initialises.

Essentially, as soon as you have any dynamic loading behaviours in the page, onPageFinished becomes meaningless, and you need to measure with JS.

As with any performance problem;

  1. measure the interaction to discover the bottlenecks
  2. try to fix a bottleneck & measure again
  3. repeat until performance is acceptable.



回答3:


To get page loading finish, use

webView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        // do your stuff here
    }
});


来源:https://stackoverflow.com/questions/24897917/can-you-measure-the-time-it-takes-to-load-a-web-page-in-a-webview-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!