I want to write an event for different modes of Wi-Fi connection and mobile data.
Exactly the same as the phone's system performance!
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);
}
}
}
You have to modify your code to work properly.
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);
}
}
}
make sure that you add this line to your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I think also that you mistaken when you add this code:
else if (wifiType.isConnectedOrConnecting() || mobileType.isConnectedOrConnecting()) {
wifi.setVisibility(View.VISIBLE);
data.setVisibility(View.VISIBLE);
}
It doesn't have any sense because you already test if one of them is connected so I suggest to change the code instead:
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);
}
}
}