Skip to content Skip to sidebar Skip to footer

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 reconne

Solution 1:

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(newWebViewClient() {

        @OverridepublicvoidonReceivedError(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.

publicclassNetworkChangeReceiverextendsBroadcastReceiver {

@OverridepublicvoidonReceive(final Context context, final Intent intent) {
    finalConnectivityManagerconnMgr= (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

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

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

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

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

And the check here:

publicbooleanisOnline(Context context) {

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

Post a Comment for "How To Detect When Loses/ Interrupted Connection In Webview?"