Android:持续检查互联网访问

时间:2015-08-19 08:59:29

标签: android connection android-internet

除此之外:

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

或ping任何服务器

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

类似于棒棒糖在连接到某些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();
}

2 个答案:

答案 0 :(得分:0)

有广播知道连接状态。您可以在此question

中获取更多信息

答案 1 :(得分:0)

在您的清单文件中添加以下内容:

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

现在手动打开和关闭网络以查看效果。