【问题标题】:Android: check internet access continuouslyAndroid:不断检查互联网访问
【发布时间】:2015-11-12 11:34:19
【问题描述】:

除此之外:

InetAddress.getByName("www.xy.com").isReachable(timeout)

或 ping 到任何服务器

还有其他方法可以持续检查设备是否可以访问互联网。我的意思是不只是连接到任何网络,而是实际访问互联网。

类似于 lollipop 在连接到某个 WIFI 网络但 WIFI 网络无法访问互联网并显示感叹号时所做的事情。

注意: 我已经知道以下内容,并且可以正常检测到连接更改

<receiver android:name=".MyReceiver" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

if (netInfo != null && netInfo.isConnectedOrConnecting()) {
    isConnected = true;
    networkName = netInfo.getTypeName();
    networkType = netInfo.getType();
}

【问题讨论】:

    标签: android connection android-internet


    【解决方案1】:

    有一个广播可以知道连接状态。你可以在这个question获得更多信息

    【讨论】:

      【解决方案2】:

      在您的清单文件中添加这些:

      <receiver android:name=".YOURRECEIVERNAME">
         <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
         </intent-filter>
      </receiver>
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      

      然后像下面这样创建java类:

      public class YOURRECEIVERNAME extends BroadcastReceiver {
          private static final String TAG = "NetworkStateReceiver";
      
          @Override
          public void onReceive(final Context context, final Intent intent) {
      
              Log.d(TAG, "Network connectivity change");
      
              if (intent.getExtras() != null) {
                  final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                  final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
      
                  if (ni != null && ni.isConnectedOrConnecting()) {
                      Log.i(TAG, "Network " + ni.getTypeName() + " connected");
                  } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
                      Log.d(TAG, "There's no network connectivity");
                  }
              }
          }
      }
      

      现在手动开关网络看看效果。

      【讨论】:

        猜你喜欢
        • 2016-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 2019-12-29
        • 1970-01-01
        相关资源
        最近更新 更多