100

I already have this code which listens to connectivity change -

public class NetworkStateReceiver extends BroadcastReceiver
{
  public void onReceive(Context context, Intent intent)
  {
    Log.d("app","Network connectivity change");

    if(intent.getExtras() != null)
    {
      NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
      if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED)
      {
        Log.i("app", "Network " + ni.getTypeName() + " connected");
      }
    }

    if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE))
    {
      Log.d("app", "There's no network connectivity");
    }
  }
}

And I check Internet connectivity using this code - Internet Check

But the problem is that if network suddenly loses internet connection without any connectivity change, this code is useless. Is there any way to create Broadcast Receiver listener for Internet connectivity change? I have a web app and sudden Internet connectivity changes can cause problems.

Community
  • 1
  • 1
Confuse
  • 5,646
  • 7
  • 36
  • 58
  • refer to this https://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app – lenhuy2106 Jan 18 '18 at 21:35

13 Answers13

110

Try this

public class NetworkUtil {
    public static final int TYPE_WIFI = 1;
    public static final int TYPE_MOBILE = 2;
    public static final int TYPE_NOT_CONNECTED = 0;
    public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
    public static final int NETWORK_STATUS_WIFI = 1;
    public static final int NETWORK_STATUS_MOBILE = 2;

    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static int getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        int status = 0;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = NETWORK_STATUS_WIFI;
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = NETWORK_STATUS_MOBILE;
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = NETWORK_STATUS_NOT_CONNECTED;
        }
        return status;
    }
}

And for the BroadcastReceiver

public class NetworkChangeReceiver extends BroadcastReceiver {

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

        int status = NetworkUtil.getConnectivityStatusString(context);
        Log.e("Sulod sa network reciever", "Sulod sa network reciever");
        if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
            if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
                new ForceExitPause(context).execute();
            } else {
                new ResumeForceExitPause(context).execute();
            }
       }
    }
}

Don't forget to put this into your AndroidManifest.xml

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.INTERNET" />
 <receiver
        android:name="NetworkChangeReceiver"
        android:label="NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>

Hope this will help you Cheers!

Cjames
  • 1,852
  • 1
  • 20
  • 23
  • 9
    why would you need to check if (!"android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) ???? – Shridutt Kothari Apr 02 '15 at 12:04
  • @shriduttkothari I use it for downloading functionality – Cjames May 04 '16 at 13:28
  • :@Cjames But "android.intent.action.BOOT_COMPLETED" does not have anything to do with downloading functionality or Network connectivity, so i think it's irrrelevant in the above code. isn't it? – Shridutt Kothari May 04 '16 at 15:15
  • 2
    It is not working in gionee s plus device.......any other way to do this ? – Himanshu Dec 03 '16 at 06:43
  • 2
    This works well except for one problem. I'm also trying to have a listener for the LAN/Ethernet connection to my Android TV Box. This works great for WiFi or Mobile connections, but not for LAN connection. I have this code that checks the state of the LAN connection, but I need a listener to catch any changes in the internet state, not just the WiFi or Mobile network: `code` NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); `code` – Wayne Johnson May 03 '17 at 16:26
  • 47
    Registering a receiver like this in your Manifest to receive connectivity change events will no longer work on Android 7.0+ https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html#MonitorChanges – w3bshark Jul 17 '17 at 17:43
  • 2
    Found a special case for network connectivity saying there is no internet but actually there is. It turns out `getActiveNetworkInfo` will always return you **DISCONNECTED/BLOCKED** in a specific case when network is changed while battery level is low and app was just switched Check out this post: https://stackoverflow.com/questions/34884442/android-checking-network-connectivity-return-not-connected-when-connected-to-wi/45231746#45231746 – Phil Jul 21 '17 at 07:51
  • 1
    i cant find ForceExitPause and ResumeForceExitPause – Pouria Hemi Apr 06 '19 at 11:33
  • you can register the receiver just directly at your activity. On destroy, don't forget to unregister again! – larsaars Apr 25 '20 at 13:16
  • hello, can you explain why is needed to add these permissions and the receiver in the android manifest? thank you c: – ladytoky0 May 25 '22 at 14:54
  • 1
    @ladytoky0 Because you need to have specific action to check & listen to the broadcast related to that action. So if you want to listen it in your app globally, then you have to declare it in manifest. So that whenever a broadcast gets broadcasted across the system, it gets received in all apps who have registered broadcast receiver in gloabally (in manifest). – Dev4Life May 26 '22 at 05:34
68

ConnectivityAction is deprecated in api 28+. Instead you can use registerDefaultNetworkCallback as long as you support api 24+.

In Kotlin:

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
    it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            //take action when network connection is gained
        }
        override fun onLost(network: Network?) {
            //take action when network connection is lost
        }
    })
}
bmjohns
  • 6,344
  • 1
  • 33
  • 39
49

Here's the Java code using registerDefaultNetworkCallback (and registerNetworkCallback for API < 24):

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network available
    }

    @Override
    public void onLost(Network network) {
        // network unavailable
    }
};

ConnectivityManager connectivityManager =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
    NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
    connectivityManager.registerNetworkCallback(request, networkCallback);
}
algrid
  • 5,600
  • 3
  • 34
  • 37
  • 3
    `NetworkRequest` requires minimum API level 21. What can we do for API level 19? – Aliton Oliveira Dec 11 '19 at 16:38
  • does this be added in broadcast receiver? it does register the callback, so I am confused. – A_rmas Aug 25 '20 at 18:26
  • 1
    @AlitonOliveira Unless you have a reason to keep supporting API 19, I would really advise dropping support for APIs below 21, Since (according to Google) 94.1% of Android users are on API 21 and above. Also, API 21 is a really sweet spot for a lot of newer APIs you'll be surprised how much unnecessary code for backwards compatibility you'll remove from your codebase. – Heysem Katibi Mar 03 '21 at 21:39
  • @algrid I would like to confirm this works on physical device, but on emulator does not. When connection is lost on emulator, onAvaiable is triggered also. – I.Step May 20 '21 at 15:17
  • This works fine when network changes occurs, but this code does not detect initial state of network. Callback is not called when app starts. Anyway around this? – hiddeneyes02 Apr 03 '22 at 07:15
44

Update:

Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

You need to register the receiver via registerReceiver() method:

 IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
 mCtx.registerReceiver(new NetworkBroadcastReceiver(), intentFilter);
Silvia H
  • 8,097
  • 7
  • 30
  • 33
  • I'm not getting my broadcast receiver called even with this code on 8.0. – TheRealChx101 Feb 02 '19 at 01:11
  • @TheRealChx101, if the context is still valid you should be good to go. What context have you used? – Tomer Petel Feb 20 '19 at 07:30
  • @TheRealChx101 The `"android.net.conn.CONNECTIVITY_CHANGE"` string is actually the `CONNECTIVITY_ACTION` constant. As you'll see at https://developer.android.com/reference/android/net/ConnectivityManager#CONNECTIVITY_ACTION , this constant was deprecated in API 28. Could your problem be to do with that? – ban-geoengineering Apr 17 '19 at 18:58
  • If I want detect network type, eg 2g,4g,can this answer be used? – Hoo Jun 03 '22 at 03:16
32

This should work:

public class ConnectivityChangeActivity extends Activity {

    private BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("app","Network connectivity change");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();

        unregisterReceiver(networkChangeReceiver);
    }
}
Manuel Schmitzberger
  • 5,162
  • 3
  • 36
  • 45
9

I used this method as a connection listener. Working for Lolipop+, Android JAVA language.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest networkRequest = new NetworkRequest.Builder().build();
    connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            Log.i("Tag", "active connection");
        }

        @Override
        public void onLost(Network network) {
            super.onLost(network);
            Log.i("Tag", "losing active connection");
            isNetworkConnected();
        }
    });
}

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected())) {
        //Do something
        return false;
    }
    return true;
}

And also add this permission in your Android Manifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Lakpriya Senevirathna
  • 2,488
  • 2
  • 17
  • 35
  • 2
    Based on a commenter that said: "This works fine when we have single connection i.e. Mobile data or Wifi. But when I am using both and turned one of them off, then also it triggers onLost() whereas I have internet connectivity. " My guess is the second portion of the code called isNetworConnected prevents a false positive rigth?? – Delark Sep 15 '21 at 19:06
  • 1
    Yes. sometimes the method goes mad with the first method. So I added isNetworkConneted() to make sure the connection lost! – Lakpriya Senevirathna Sep 23 '21 at 11:35
  • 2
    @Delark, In my case, if the phone is connected to both, `onLost()` is called only when wifi is turned off . Mobile data state change doesn't trigger the callback, as long as wifi is on. Pixel 3a XL , android 12. – Sam Nov 24 '21 at 19:35
  • 1
    @LakpriyaSenevirathna, I have noticed that when the phone is connected to both wif & data, calling `isNetworkConnected()` returns `false` when wifi is turned off, even though mobile data is still on. What I did is, I called it after 100-200 milliseconds delay and it returns `true` as expected. – Sam Nov 24 '21 at 19:57
  • 1
    I modified it a bit though: `if(cm != null){NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting() && (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE); } return false;` – Sam Nov 24 '21 at 19:58
  • 2
    Thanks @Sam, I've had some issues in my todo list, and I thought it had something to do with some concurrency issues on the stream, but now that I think about it , it may very well be this the problem since my wifi sometimes disconnects, I think it may also arise in non SIM devices, that are connected with wifi only, since I've tried reconnecting to the wifi (which is supposed to be working fine), and no reaction occurs, and a hard listener reconnection (un-register then register) is required. – Delark Nov 24 '21 at 22:05
  • 1
    What I am afraid of is that maybe we should not be checking for a "successful" connection (with `cm.getActiveNetworkInfo().isConnected()`) instead we should be checking for a "failure" since we may return a false negative before the device has "timed out" it's attempted connections during these 200 Millis. Unless its "time out" chronometer is exactly 200 Millis lol... But thinking more about it , this may over complicate things since I may be adding a third state in what should be a true or false event. So maybe a 200 Millis is the correct thing to do. – Delark Nov 24 '21 at 22:05
  • 2
    @Sam BTW don't forget to synchronize the boolean output since a reconnection may become true, BEFORE the 200 Millis callback "dispatched" a false. – Delark Nov 24 '21 at 22:12
5

Hello from the year 2022.

In my custom view model I observe network status changes like this:

public class MyViewModel extends AndroidViewModel {
    private final MutableLiveData<Boolean> mConnected = new MutableLiveData<>();

    public MyViewModel(Application app) {
        super(app);

        ConnectivityManager manager = (ConnectivityManager)app.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (manager == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            mConnected.setValue(true);
            return;
        }

        NetworkRequest networkRequest = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .build();

        manager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
            Set<Network> availableNetworks = new HashSet<>();

            public void onAvailable(@NonNull Network network) {
                availableNetworks.add(network);
                mConnected.postValue(!availableNetworks.isEmpty());
            }

            public void onLost(@NonNull Network network) {
                availableNetworks.remove(network);
                mConnected.postValue(!availableNetworks.isEmpty());
            }

            public void onUnavailable() {
                availableNetworks.clear();
                mConnected.postValue(!availableNetworks.isEmpty());
            }
        });
    }

    @NonNull
    public MutableLiveData<Boolean> getConnected() {
        return mConnected;
    }
}

And then in my Activity or Fragment I can change the UI by observing:

@Override
protected void onCreate(Bundle savedInstanceState) {
    MyViewModel vm = new ViewModelProvider(this).get(MyViewModel.class);

    vm.getConnected().observe(this, connected -> {
        // TODO change GUI depending on the connected value
    });
}
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
  • 1
    This answer was good, just implement it in activity/fragment to listen for network changes and do something if the value is true/false – Liew Syet Chau Mar 30 '22 at 02:23
  • 1
    It is not correct to assume no connection when onLost is called. If there's e.g. Wifi and Cellular, onAvailable is called twice. When you lose Wifi, onLost is called, but you still have Cellular. Have a look at Xid's answer for how to handle this correctly. It works perfectly. – Ridcully Dec 20 '22 at 12:15
4
  1. first add dependency in your code as implementation 'com.treebo:internetavailabilitychecker:1.0.4'
  2. implements your class with InternetConnectivityListener.
public class MainActivity extends AppCompatActivity implements InternetConnectivityListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        InternetAvailabilityChecker.init(this);
        mInternetAvailabilityChecker = InternetAvailabilityChecker.getInstance();
        mInternetAvailabilityChecker.addInternetConnectivityListener(this);
    }

    @Override
    public void onInternetConnectivityChanged(boolean isConnected) {
        if (isConnected) {
            alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle(" internet is connected or not");
            alertDialog.setMessage("connected");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.show();

    }
    else {
            alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("internet is connected or not");
            alertDialog.setMessage("not connected");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.show();

        }
    }
}
Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
3

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)
Ibrahim Ali
  • 1,237
  • 9
  • 20
3

According to the official docs:

  1. Define network request
private val networkRequest = NetworkRequest.Builder().apply {
    // To check wifi and cellular networks for internet availability
    addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Capabilities can be verified starting Android 6.0.
        // For a network with NET_CAPABILITY_INTERNET, 
        // it means that Internet connectivity was successfully detected
        addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        // Indicates that this network is available for use by apps,
        // and not a network that is being kept up in the background 
        // to facilitate fast network switching.
        addCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND)
    }
}.build()
  1. Configure a network callback
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
    private val networks = mutableListOf<Network>()

    override fun onAvailable(network: Network) {
        super.onAvailable(network)

        networks.add(network)
        Log.d("Has network --->", networks.any().toString())
    }

    override fun onLost(network: Network) {
        super.onLost(network)

        networks.remove(network)
        Log.d("Has network --->", networks.any().toString())
    }
}
  1. Register for network updates
val connectivityService =
    applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityService.registerNetworkCallback(networkRequest, networkCallback)
Xid
  • 4,578
  • 2
  • 13
  • 35
  • 1
    Network implements hashCode & equals, so in onLost() a simple networks.remove(network) should be fine. – Ridcully Dec 20 '22 at 12:10
2

Answering this in 2023, Since a better implementation is available

NetworkObserver.kt

/**
 * This class is in charge of listening to the state of the network connection and notifying the
 * activity if the state of the connection changes.
 * */
class NetworkObserver constructor(
    private val context: Context,
    private val lifecycle: Lifecycle
  ) : DefaultLifecycleObserver {

  private lateinit var networkCallback: ConnectivityManager.NetworkCallback
  private var connectivityManager: ConnectivityManager? = null
  private val validNetworks = HashSet<Network>()

  private lateinit var job: Job
  private lateinit var coroutineScope: CoroutineScope

  // State Holder: Indicating either the network is available or not-available
  private val _networkAvailableStateFlow: MutableStateFlow<NetworkState> = MutableStateFlow(NetworkState.Available)

  val networkAvailableStateFlow
    get() = _networkAvailableStateFlow

  // ---> This variable can be accessed anytime to get the current state of the network
  val isConnected: Boolean
    get() = _isConnected.get()

  private val _isConnected = AtomicBoolean(false)

  override fun onCreate(owner: LifecycleOwner) {
    super.onCreate(owner)
    init()
  }

  override fun onStart(owner: LifecycleOwner) {
    super.onStart(owner)
    registerNetworkCallback()
    checkValidNetworks()
  }

  override fun onStop(owner: LifecycleOwner) {
    super.onStop(owner)
    unregisterNetworkCallback()
  }

  private fun init() {
    // Initialize the connectivity manager instance
    connectivityManager = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
  }

  private fun registerNetworkCallback() {
    if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
      // Observing the network should happen only when the life-cycle is in started state
      initCoroutine()
      initNetworkMonitoring()
    }
  }

  private fun unregisterNetworkCallback() {
    validNetworks.clear()
    connectivityManager?.unregisterNetworkCallback(networkCallback)
    job.cancel()
  }

  /**
   * Co-Routine used to monitor the connectivity
   */
  private fun initCoroutine() {
    // Create a job instance
    job = Job()
    // Provide a co-routine scope
    coroutineScope = CoroutineScope(Dispatchers.Default + job)
  }

  private fun initNetworkMonitoring() {
    networkCallback = createNetworkCallback()

    val networkRequest = NetworkRequest.Builder()
        .addCapability(NET_CAPABILITY_INTERNET)
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .build()
    connectivityManager?.registerNetworkCallback(networkRequest, networkCallback)
  }

  private fun createNetworkCallback() = object : ConnectivityManager.NetworkCallback() {
    override fun onAvailable(network: Network) {
      connectivityManager?.getNetworkCapabilities(network).also {
        if (it?.hasCapability(NET_CAPABILITY_INTERNET) == true) {
          validNetworks.add(network)
        }
      }
      checkValidNetworks()
    }

    override fun onLost(network: Network) {
      validNetworks.remove(network)
      checkValidNetworks()
    }
  }

  private fun checkValidNetworks() {
    coroutineScope.launch {
      _networkAvailableStateFlow.emit(
          if (validNetworks.size > 0){
            _isConnected.set(true)
            NetworkState.Available
          } else {
            _isConnected.set(false)
            NetworkState.Unavailable
          }
      )
    }
  }
}

sealed class NetworkState {
  object Unavailable : NetworkState()
  object Available : NetworkState()
}

Usage

    // --> Initialize the network observer in your activity or fragment
    networkObserver = NetworkObserver(this, lifecycle)
    lifecycle.addObserver(networkObserver)

    // --> Use live data to observe the network changes
    networkObserver.networkAvailableStateFlow.asLiveData().observe(this, Observer { networkState ->
      when (networkState) {
        NetworkState.Unavailable -> SnackBarDisplay.showNetworkUnavailableAlert(binding.root)
        NetworkState.Available -> SnackBarDisplay.removeNetworkUnavailableAlert()
      }
    })

I have posted full solution in my GitHub here

Devrath
  • 42,072
  • 54
  • 195
  • 297
1

ref https://developer.android.com/training/monitoring-device-state/connectivity-status-type

To specify the transport type of the network, such as Wi-Fi or cellular connection, and the currently connected network's capabilities, such as internet connection, you must configure a network request.

Declare a NetworkRequest that describes your app’s network connection needs. The following code creates a request for a network that is connected to the internet and uses either a Wi-Fi or cellular connection for the transport type.

add this in onCreate

NetworkRequest networkRequest = new NetworkRequest.Builder()
    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
    .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
    .build();

Configure a network callback When you register the NetworkRequest with the ConnectivityManager, you must implement a NetworkCallback to receive notifications about changes in the connection status and network capabilities.

The most commonly implemented functions in the NetworkCallback include the following:

onAvailable() indicates that the device is connected to a new network that satisfies the capabilities and transport type requirements specified in the NetworkRequest. onLost() indicates that the device has lost connection to the network. onCapabilitiesChanged() indicates that the capabilities of the network have changed. The NetworkCapabilities object provides information about the current capabilities of the network.

add listener

private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
    super.onAvailable(network);
}

@Override
public void onLost(@NonNull Network network) {
    super.onLost(network);
}

@Override
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
    super.onCapabilitiesChanged(network, networkCapabilities);
    final boolean unmetered = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
}};

Register for network updates After you declare the NetworkRequest and NetworkCallback, use the requestNetwork() or registerNetworkCallback() functions to search for a network to connect from the device that satisfies the NetworkRequest. The status is then reported to the NetworkCallback.

Register in onCreate

ConnectivityManager connectivityManager =
    (ConnectivityManager) getSystemService(ConnectivityManager.class);
connectivityManager.requestNetwork(networkRequest, networkCallback);
manu mathew
  • 81
  • 1
  • 4
-3

implementation 'com.treebo:internetavailabilitychecker:1.0.1'

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        InternetAvailabilityChecker.init(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
    }
}
Lennoard Silva
  • 767
  • 1
  • 8
  • 17
Hans Cruz
  • 1
  • 1