如何检测 Webview 中何时丢失/中断连接? [英] How to detect when loses/ interrupted connection in Webview?

查看:33
本文介绍了如何检测 Webview 中何时丢失/中断连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个 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.

推荐答案

这看起来像是 这篇文章.但相关的代码块在下面.这是一种捕获错误并相应地更改用户界面的方法.

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);
        }
    });

您还可以使用广播接收器侦听整个应用中的网络连接丢失情况.您可以在此处找到一篇不错的文章.但要点是您为网络更改注册接收器,然后检查更改是否断开连接.然后你可以使用你自己的事件总线发送一个可以更新你的 UI 的广播.

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");
    }
  }
} 

还有这里的检查:

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());
}

这篇关于如何检测 Webview 中何时丢失/中断连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆