Android: Internet connectivity change listener
Asked Answered
W

13

102

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.

Watershed answered 5/9, 2014 at 3:28 Comment(1)
refer to this #15699290Mote
D
111

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!

Distinguish answered 5/9, 2014 at 3:42 Comment(11)
why would you need to check if (!"android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) ????Tyratyrannical
@shriduttkothari I use it for downloading functionalityDistinguish
:@Distinguish 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?Tyratyrannical
It is not working in gionee s plus device.......any other way to do this ?Shepley
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(); codeShayla
Registering a receiver like this in your Manifest to receive connectivity change events will no longer work on Android 7.0+ developer.android.com/training/monitoring-device-state/…Pachalic
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: #34884942Detriment
i cant find ForceExitPause and ResumeForceExitPauseStarlastarlene
you can register the receiver just directly at your activity. On destroy, don't forget to unregister again!Mehitable
hello, can you explain why is needed to add these permissions and the receiver in the android manifest? thank you c:Tip
@Tip 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).Intransigent
P
72

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
        }
    })
}
Paraglider answered 29/3, 2019 at 17:16 Comment(6)
Correct !! This is most valid answer of 2019 :)Marlenemarler
Call requires API level 24 still is very big as for 2019-2020Telford
@Telford you can use connectivityManager.registerNetworkCallbackProtege
there is also ConnectivityManager.registerNetworkCallback which work for 21+Protege
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. Do you know why this happens or how can we handle this case?Sculpsit
@Sculpsit Were you able to figure out the solution?Skat
L
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);
}
Lessor answered 19/10, 2019 at 21:7 Comment(5)
NetworkRequest requires minimum API level 21. What can we do for API level 19?Westbound
does this be added in broadcast receiver? it does register the callback, so I am confused.Stannwood
@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.Unload
@Lessor 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.Permanence
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?Taco
E
45

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);
Enciso answered 13/3, 2018 at 11:45 Comment(4)
I'm not getting my broadcast receiver called even with this code on 8.0.Springspringboard
@TheRealChx101, if the context is still valid you should be good to go. What context have you used?Kempe
@Springspringboard The "android.net.conn.CONNECTIVITY_CHANGE" string is actually the CONNECTIVITY_ACTION constant. As you'll see at developer.android.com/reference/android/net/… , this constant was deprecated in API 28. Could your problem be to do with that?Diathesis
If I want detect network type, eg 2g,4g,can this answer be used?Matrilocal
M
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);
    }
}
Manutius answered 25/6, 2018 at 9:5 Comment(5)
THANKS!! The simplest solution in a little bti of linesBrunobruns
How can check whether the internet is connected or disconnected?Mudpack
@Mudpack I used this answer to determine whether there was a connection or not: https://mcmap.net/q/11338/-detect-whether-there-is-an-internet-connection-available-on-android-duplicateFauve
This does not tell you whether internet is available. It only tells you whether you have network.Abortive
If I want detect network type, eg 2g,4g,can this answer be used?Matrilocal
B
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" />
Burschenschaft answered 7/3, 2021 at 13:50 Comment(8)
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??Apollonius
Yes. sometimes the method goes mad with the first method. So I added isNetworkConneted() to make sure the connection lost!Burschenschaft
@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.Hora
@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.Hora
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;Hora
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.Apollonius
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.Apollonius
@Hora BTW don't forget to synchronize the boolean output since a reconnection may become true, BEFORE the 200 Millis callback "dispatched" a false.Apollonius
S
7

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
    });
}
Seminarian answered 20/3, 2022 at 15:22 Comment(2)
This answer was good, just implement it in activity/fragment to listen for network changes and do something if the value is true/falseMaturity
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.Frustrate
W
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();

        }
    }
}
Waistline answered 18/9, 2019 at 11:21 Comment(0)
C
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)
Catchascatchcan answered 18/1, 2021 at 15:18 Comment(0)
L
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)
Luana answered 12/7, 2022 at 14:4 Comment(1)
Network implements hashCode & equals, so in onLost() a simple networks.remove(network) should be fine.Frustrate
E
3

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

Excavation answered 1/3, 2023 at 14:8 Comment(0)
P
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);
Purgatorial answered 8/9, 2022 at 8:43 Comment(0)
A
-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();
    }
}
Arraignment answered 8/1, 2020 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.