Checking Device has internet connection

2019-09-21 15:00发布

问题:

I followed this Keep checking if Device has internet connection to check internet connectivity using

BroadcastReceiver, the problem is how to call this

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

from main activity

回答1:

     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;

}


回答2:

You have two options

1. in your MainActivity.java

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

2. In manifest file

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