I am trying to implement a TimeOut error handling on a webview. But unfortunately I am doing something wrong, which is causing me huge headaches. Currently I am using a TimerTask
. To check the progress of a webpage for 10 seconds. The idea is if the page takes more than 10 seconds to load, the app should display a custom "no I-net" view.
Here is my code so far:
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (mNoInternetConnectionView.getVisibility() == View.VISIBLE) {
mNoInternetConnectionView.setVisibility(View.GONE);
}
mTimer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (webView.getProgress() < 100) {
handleInternetProblems();
}
}
});
}
};
mTimer.schedule(timerTask, 10000, 1);
}
@Override
public void onPageFinished(WebView view, String url) {
cancelTimer();
if (!internetError && webView.getVisibility() != View.VISIBLE) {
webView.setVisibility(View.VISIBLE);
}
}
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return mCheckoutUrlHandler.handleUrl(webView, url);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return true;
}
@Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
//handle ssl error
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
handleInternetProblems();
}
});
And here are my handleInternetProblems()
and my cancelTimer()
:
private void handleInternetProblems() {
internetError = true;
webView.setVisibility(View.GONE);
mNoInternetConnectionView.setVisibility(View.VISIBLE);
mKLLoadingAnimation.hide();
cancelTimer();
}
private void cancelTimer() {
if (mTimer != null) {
mTimer.cancel();
mTimer.purge();
mTimer = null;
}
}
The problem is that if I click on an URL on the webview and I try to load another webpage I get mNoInternetConnectionView
and I can see that handleInternetProblems()
is called multiple times inside TimerTask
. What am I doing wrong? How can I prevent this from happening?