1ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
2 @Override
3 public void onAvailable(Network network) {
4 // network available
5 }
6
7 @Override
8 public void onLost(Network network) {
9 // network unavailable
10 }
11};
12
13ConnectivityManager connectivityManager =
14 (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
15
16if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
17 connectivityManager.registerDefaultNetworkCallback(networkCallback);
18} else {
19 NetworkRequest request = new NetworkRequest.Builder()
20 .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
21 connectivityManager.registerNetworkCallback(request, networkCallback);
22}
23
1val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
2connectivityManager?.let {
3 it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
4 override fun onAvailable(network: Network) {
5 //take action when network connection is gained
6 }
7 override fun onLost(network: Network?) {
8 //take action when network connection is lost
9 }
10 })
11}
12