我想为不同模式的Wi-Fi连接和移动数据编写一个事件。
- 如果 Wi-Fi 已打开且移动数据已关闭,则 Wi-Fi 图标将可见
- 如果移动数据已打开且 Wi-Fi 已关闭,则移动数据图标将可见
- 如果两者都打开,则两个图标都可见
- 如果两者都关闭,图标将消失
- 如果两个都打开,其中一个熄灭,则熄灭的图标将熄灭
与手机的系统性能完全相同!
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifiType = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobileType = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifiType.isConnectedOrConnecting()) {
wifi.setVisibility(View.VISIBLE);
} else if (mobileType.isConnectedOrConnecting()) {
data.setVisibility(View.VISIBLE);
} else if (wifiType.isConnectedOrConnecting() || mobileType.isConnectedOrConnecting()) {
wifi.setVisibility(View.VISIBLE);
data.setVisibility(View.VISIBLE);
} else {
wifi.setVisibility(View.GONE);
data.setVisibility(View.GONE);
}
}
}
您必须修改代码才能正常工作。
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo[] activeNetworkInfo = connectivityManager.getAllNetworkInfo();
for (NetworkInfo ni : activeNetworkInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
{
wifi.setVisibility(View.VISIBLE);
} else if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
{
data.setVisibility(View.VISIBLE);
}else {
wifi.setVisibility(View.GONE);
data.setVisibility(View.GONE);
}
}
}
请确保将此行添加到清单中:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我还认为您在添加此代码时弄错了:
else if (wifiType.isConnectedOrConnecting() || mobileType.isConnectedOrConnecting()) {
wifi.setVisibility(View.VISIBLE);
data.setVisibility(View.VISIBLE);
}
它没有任何意义,因为您已经测试了其中一个是否已连接,所以我建议改为更改代码:
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
assert connectivityManager != null;
NetworkInfo[] activeNetworkInfo = connectivityManager.getAllNetworkInfo();
for (NetworkInfo ni : activeNetworkInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
{
wifi.setVisibility(View.VISIBLE);
} else {
wifi.setVisibility(View.GONE);
}
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
{
data.setVisibility(View.VISIBLE);
}
else {
data.setVisibility(View.GONE);
}
}
}