Home > Java > javaTutorial > body text

How to Detect Network Connectivity Changes in Android?

DDD
Release: 2024-10-25 01:40:30
Original
885 people have browsed it

How to Detect Network Connectivity Changes in Android?

Implementing Network Listener in Android

Question:

Can we monitor network connectivity changes on an Android device and capture events when the network goes offline?

Answer:

Yes, it is possible to listen for network connectivity changes in Android. Here's a detailed implementation:

1. Create a Broadcast Receiver:

<code class="java">public class ConnectionChangeReceiver extends BroadcastReceiver {
  ...
  @Override
  public void onReceive(Context context, Intent intent) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
    NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    // Check for active network and mobile network changes
    ...
  }
  ...
}</code>
Copy after login

2. Declare Permission:

<code class="xml"><!-- Required to monitor network connectivity changes -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /></code>
Copy after login

3. Register Receiver in AndroidManifest.xml:

<code class="xml"><receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver"
          android:label="NetworkConnection">
  <intent-filter>
    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
  </intent-filter>
</receiver></code>
Copy after login

Explanation:

The broadcast receiver registers itself to listen for "CONNECTIVITY_CHANGE" broadcasts from the system. When the network status changes, the onReceive() method is triggered, and the receiver can check the current network state and respond accordingly.

The above is the detailed content of How to Detect Network Connectivity Changes in Android?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!