检查设备是否有Internet连接

时间:2016-06-02 13:18:40

标签: android android-wifi android-networking

我按照此Keep checking if Device has internet connection使用

检查互联网连接

BroadcastReceiver,问题是如何调用此

registerReceiver(mConnReceiver, 
       new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

来自主要活动

2 个答案:

答案 0 :(得分:0)

     Try this:


     if(isNetworkStatusAvialable(getApplicationContext()))
 {
 }else
 {

      public static boolean isNetworkStatusAvialable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
        if (netInfos != null)
            if (netInfos.isConnected())
                if (netInfos.isAvailable())
                    return true;
    }
    return false;

}

答案 1 :(得分:0)

您有两个选择

<强> 1。在MainActivity.java

 // create object of receiver class 
 NetworkChangeReceiver mConnReceiver = new NetworkChangeReceiver();
 //register the receiver
 registerReceiver(mConnReceiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

<强> 2。在manifest档案

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