android11 监听网络变动 代码或demo
时间: 2023-09-11 11:07:18 浏览: 101
以下是一个使用BroadcastReceiver的示例程序,用于监听网络状态变化:
1.添加权限:
```xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
```
2.创建BroadcastReceiver:
```java
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//网络已连接
} else {
//网络未连接
}
}
}
```
3.在AndroidManifest.xml中注册BroadcastReceiver:
```xml
<receiver android:name=".NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
```
4.在Activity中启动BroadcastReceiver:
```java
NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(networkChangeReceiver, intentFilter);
```
5.在Activity中注销BroadcastReceiver:
```java
unregisterReceiver(networkChangeReceiver);
```
阅读全文