emenpy
emenpy

Reputation: 51

How to detect when loses/ interrupted connection in Webview?

I'm implementing a Webview and want to detect when losing connection or when the network interrupted..( ex: when the device goes out of the network range)

and to be able to reconnect when the connection re-established.

Any inputs would be appreciated. Thanks.

Upvotes: 1

Views: 1878

Answers (1)

Kyle Venn
Kyle Venn

Reputation: 8038

This looks like a duplicate of this post. But the relevant code block is below. It's a way to catch the error and change your UI accordingly.

       webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onReceivedError(final WebView view, int errorCode, String description,
                final String failingUrl) {
            //control you layout, show something like a retry button, and 
            //call view.loadUrl(failingUrl) to reload.
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });

You can also listen for network connection loss across the entire app with a broadcast receiver. You can find a nice write up here. But the gist is you register a receiver for network change, then you check if the change was a disconnect. Then you can use your own event bus to send out a broadcast that can update your UI.

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable() || mobile.isAvailable()) {
        // Do something

        Log.d("Network Available ", "Flag No 1");
    }
  }
} 

And the check here:

public boolean isOnline(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //should check null because in air plan mode it will be null
    return (netInfo != null && netInfo.isConnected());
}

Upvotes: 1

Related Questions