NetworkCallback 监听回调 WiFi切换移动数据
时间: 2024-05-16 13:16:20 浏览: 119
当 Android 设备的 WiFi 连接不稳定或信号弱时,系统可能会自动切换到移动数据网络。您可以使用 NetworkCallback 监听回调来检测这种网络切换。
以下是一个简单的示例代码,用于监听网络连接状态的变化并在网络切换到移动数据时发送通知:
```java
public class ConnectivityReceiver extends ConnectivityManager.NetworkCallback {
private Context mContext;
private NotificationManager mNotificationManager;
private static final int NOTIFICATION_ID = 123;
public ConnectivityReceiver(Context context) {
mContext = context;
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
// 网络连接成功
Log.d("ConnectivityReceiver", "Network available");
}
@Override
public void onLost(Network network) {
super.onLost(network);
// 网络连接丢失
Log.d("ConnectivityReceiver", "Network lost");
}
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
super.onCapabilitiesChanged(network, capabilities);
// 网络连接状态改变
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
// 移动数据网络连接
Log.d("ConnectivityReceiver", "Mobile data connected");
// 发送通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Network changed")
.setContentText("Switched to mobile data")
.setPriority(NotificationCompat.PRIORITY_HIGH);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
} else {
// WiFi 连接
Log.d("ConnectivityReceiver", "WiFi connected");
}
}
}
```
要使用 NetworkCallback,您需要在 AndroidManifest.xml 文件中声明 ACCESS_NETWORK_STATE 和 CHANGE_NETWORK_STATE 权限:
```xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
```
然后,您需要在您的 Activity 或 Service 中注册 ConnectivityReceiver:
```java
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
ConnectivityReceiver connectivityReceiver = new ConnectivityReceiver(this);
connectivityManager.registerDefaultNetworkCallback(connectivityReceiver);
```
这样,您就可以在网络连接状态发生变化时收到通知,包括 WiFi 切换到移动数据的事件。
阅读全文