android.net.conn.CONNECTIVITY_CHANGE broadcast rec

2019-08-07 19:37发布

问题:

This is manifest part

  <receiver
            android:name="my.com.app.ConnectivityModifiedReceiver"
            android:label="NetworkConnection" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

This is java code

public class my.com.app.ConnectivityModifiedReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {

        context.sendBroadcast(new Intent("ConnectivityModified"));

    }

}

The ConnectivityModifiedReceiver will send intents according to network connectivity change.In my case VPN connection and disconnection.

I am getting intents in Lollipop But not in JellyBean.

Plz help

回答1:

So far in my findings

In Lollipop

android.net.conn.CONNECTIVITY_CHANGE broadcast is fired Only when either VPN is connected or disconnected.

So you can use the following code snippet along with the logic you have for pre-lollipop devices.

@Override
public void onReceive(Context context, Intent intent) {

   Bundle bundle = intent.getExtras();

   String KeyNI="networkInfo";

   android.net.NetworkInfo bundleNetworkInfo=(android.net.NetworkInfo)bundle.get(KeyNI);


   if(!bundleNetworkInfo.getTypeName().toString().equalsIgnoreCase("VPN"))
   {
      context.sendBroadcast(new Intent("ConnectivityModified"));
   }

}

Hope this helps.



回答2:

You might give this a try on your onReceive if it helps:

@Override
public void onReceive(Context context, Intent intent) {
    final ConnectivityManager connMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
    // should check null because in air plan mode it will be null
    if (netInfo != null && netInfo.isConnected()) {
        System.out.println("INTERNET IS AVAILABLE");
    } else {
        System.out.println("INTERNET UNAVAILABLE");
    }
}

You can place your logic inside the if statement.