在Android应用中,可以通过注册BroadcastReceiver来监听网络连接状态的变化,从而实现监听到4G和WiFi网络切换的情况。
首先在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
然后创建一个BroadcastReceiver来监听网络连接状态的变化:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// 网络已连接
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// WiFi网络
Log.d("Network", "WiFi Connected");
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// 移动网络
Log.d("Network", "4G Connected");
}
} else {
// 网络断开
Log.d("Network", "Disconnected");
}
}
}
接着在MainActivity中注册该BroadcastReceiver:
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(networkChangeReceiver);
}
通过以上步骤,可以监听到4G和WiFi网络切换的情况,并在logcat中打印出相应的信息。如果您需要在应用中进行其他操作,可以根据实际需求在BroadcastReceiver中添加相应的逻辑处理。
在 Android 应用中监听网络状态变化,包括从 4G 到 Wi-Fi 的切换,可以通过注册一个 BroadcastReceiver 来实现。以下是一个简单的示例代码:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// Wi-Fi 连接
Log.d("NetworkChangeReceiver", "Wi-Fi 已连接");
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// 移动网络连接
Log.d("NetworkChangeReceiver", "移动网络(4G/3G/2G)已连接");
}
} else {
// 网络断开
Log.d("NetworkChangeReceiver", "网络已断开");
}
}
}
然后在你的 Activity 或者 Service 中注册该 BroadcastReceiver,监听网络状态变化:
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
NetworkChangeReceiver receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
记得在不需要监听时注销该 BroadcastReceiver:

unregisterReceiver(receiver);
这样当网络状态发生变化时,就会通过 NetworkChangeReceiver
中的 onReceive
方法监听到,并在 Logcat 中打印相应的提示信息。你可以根据监听到的网络类型做相应的处理,比如通知用户网络状态变化、切换代理等操作。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/150840.html