Home >Java >javaTutorial >How can I monitor Internet connectivity changes in my Android application?
Android: Monitoring Internet Connectivity Changes
To monitor internet connectivity changes, Android provides the ConnectivityManager.NetworkCallback class. This allows for more granular listening compared to the traditional BroadcastReceiver. Here's how to implement it:
<code class="java">public class ConnectivityMonitor extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { // Internet connectivity is available Log.d("Connectivity", "Internet connected"); } @Override public void onLost(Network network) { // Internet connectivity is lost Log.d("Connectivity", "Internet disconnected"); } }</code>
To register this callback, you need to create a ConnectivityManager instance and call the registerNetworkCallback method:
<code class="java">ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); connectivityManager.registerNetworkCallback(new NetworkRequest.Builder().build(), new ConnectivityMonitor());</code>
You can also use pre-defined connectivity states from ConnectivityManager:
<code class="java">if (connectivityManager.getActiveNetworkInfo() != null) { // Connected to a network if (connectivityManager.getActiveNetworkInfo().isConnectedToWifi()) { // Connected via WiFi } else { // Connected via mobile data } } else { // Not connected to a network }</code>
Remember to unregister the callback when you're done:
<code class="java">connectivityManager.unregisterNetworkCallback(new ConnectivityMonitor());</code>
The above is the detailed content of How can I monitor Internet connectivity changes in my Android application?. For more information, please follow other related articles on the PHP Chinese website!