Timeout on Webview Android

2019-04-09 18:50发布

Is there a way to set the timeout value in WebView? I want the WebView to be time-outed if the url is too slow to response or if the site doesn't load in 10 seconds.

I don't know really where I should start :(

I have 2 classes, the first one is starter and the second one is for webView. Starter is a kind of thread and splash-screen for start and the next activity is the main webView, so I would like to add a checker if the site doesn't response in 4 10 secs, it would give a error.

I hope any of you can help me,

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-09 19:06

You can do it by setting up a Timer which checks for progress of current page by calling getProgress() and if it is less than some threshold after some specified time then you can dismiss the loading of the current page.

查看更多
男人必须洒脱
3楼-- · 2019-04-09 19:16

Darpans code will not work, not at least because the parameter progress will not change during while, only by next call of. Try this instead:

private long starttime = 0;
public void onProgressChanged(WebView view, int progress) {
    Log.v(TAG, "progressChanged: " + progress);
    if(progress == 10) starttime = System.currentTimeMillis();

    long secondsSinceStart = (System.currentTimeMillis() - starttime) / 1000;

    if(progress < 100) {
        Log.v(TAG, "seconds since start: " + secondsSinceStart);
        if(secondsSinceStart > 5){
            view.stopLoading();
            Log.d(TAG, "TIMEOUT -> Stopped.");
        }
    } else {
        Log.v(TAG, progress + "% completed in: " + secondsSinceStart + " seconds");
    }
}

Unfortunately this will only work if the connection to the server will be established. If not the onProgressChanged get called only two times: at 10 and at 100 percents when then load is aborted.

查看更多
劫难
4楼-- · 2019-04-09 19:17

Here is the code to implement a timer that will check the progress and triggers action if it takes more than a certain time to load the page.

webView.setWebChromeClient(new WebChromeClient() {
    Long seconds = (long) 0.0;
    public void onProgressChanged(WebView view, int progress) {
        Date interestingDate = new Date();

        // second < 5 here you can use your desired time you wish to wait for.
        while (progress < 100 && seconds < 5) {
            //following line calculates time difference
            //between current time and time when page started loading.
            seconds = ((new Date()).getTime() - interestingDate.getTime())/1000;
        }

        if(progress < 100 && seconds > 5) {
            view.stopLoading();
            Log.d("###", "stopped");
        }       
    }
});
查看更多
登录 后发表回答