user430926
user430926

Reputation: 4057

Android WebView TimeOut

Is there a way to set the timeout value in WebView? I want the WebView to be timeouted if the url is too slow to response.

Upvotes: 17

Views: 28660

Answers (3)

JoaquinBu
JoaquinBu

Reputation: 401

I use

@Override
    public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
        final Dialog dialog = new Dialog(MainActivity.this, android.R.style.Theme_NoTitleBar_Fullscreen);
        dialog.setContentView(R.layout.alert_dialog);
        Button btTryAgain = dialog.findViewById(R.id.bt_try_again);
        btTryAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                recreate();
            }
        });
        dialog.show();
        //Toast with error conection
        Toast.makeText(getApplicationContext(), "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
    }

Where -alert_dialog- is a layout with a button to retry

Upvotes: 1

John
John

Reputation: 8946

We can use onLoadResource method of WebViewClient instead of Timer. Like this:

webView.setWebViewClient(new WebViewClient() {

    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return false;
    }

    @Override 
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        progressDialog.show();
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        Log.d("WEBCLIENT", "onPageFinished");
    }

    @Override 
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);
        Log.d("WEBCLIENT","onLoadResource");

        if(webView.getProgress() == 100) {
            progressDialog.dismiss();
        }    
    }
}

Upvotes: 5

bhups
bhups

Reputation: 14885

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.

Upvotes: 11

Related Questions