Raghuram db Raghuram db - 3 months ago 86
Android Question

ConnectivityManager.CONNECTIVITY_ACTION deprecated

In Android N, it is mentioned on the official website that "Apps targeting Android N do not receive CONNECTIVITY_ACTION broadcasts". And it is also mentioned that

can be used as an alternative. But the
doesn't provide exactly the same behavior as

In my Android application, I was using this broadcast to know the network state of the device. I wanted to know if this state was
with the help of
broadcast and it was best suited for my requirement.

Now that it is deprecated, can any one suggest me the alternative approach to get current network state?


What will be deprecated is the ability for a backgrounded application to receive network connection state changes.

As David Wasser said you can still get notified of connectivity changes if your app is running in the foreground and you have registered your receiver programmatically, instead of doing it in the manifest.

Or you can use NetworkCallback instead. In particular, you will need to override onAvailable for connected state changes.

Let me draft a snippet quickly:

public class ConnectionStateMonitor extends NetworkCallback {

   final NetworkRequest networkRequest;

   public ConnectionStateMonitor() {
       networkRequest = new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR).addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();

   public void enable(Context context) {
       ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);


   // Likewise, you can have a disable method that simply calls ConnectivityManager#unregisterCallback(networkRequest) too.

   public void onAvailable(Network network) {
       // Do what you need to do here