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
Release: 2024-10-29 11:15:02
Original
688 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

Remember to unregister the callback when you're done:

<code class="java">connectivityManager.unregisterNetworkCallback(new ConnectivityMonitor());</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template