Home >Java >javaTutorial >How can I monitor Internet connectivity changes in my Android application?

How can I monitor Internet connectivity changes in my Android application?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 11:15:02614browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn