I was trying to check if the device is connected to internet and what is the network type. Here is an example of how we check it in android
public boolean isConnectingToInternet(Activity act){
boolean isthere = false;
TelephonyManager tm = (TelephonyManager) act.getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() != TelephonyManager.SIM_STATE_UNKNOWN){
ConnectivityManager connectivityManager = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED))
isthere = true;
} else {
ConnectivityManager connectivityManager = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED))
isthere = true;
}
return isthere;
}
Add permission ohos.permission.GET_NETWORK_INFO, which is used to obtain network information. Add permission ohos.permission.INTERNET, which is used to access the network.
• Check if network is connected
public static boolean hasInternetConnection(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED);
}
• Check if WiFi is connected
public static boolean isWifiConnectedInternet(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED) &&
netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI) ||
netCapabilities.hasBearer(NetCapabilities.BEARER_WIFI_AWARE);
}
• Check if Mobile network is connected
public static boolean isMobileConnectedInternet(Context context) {
NetManager netManager = NetManager.getInstance(context);
NetCapabilities netCapabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
return netCapabilities.hasCap(NetCapabilities.NET_CAPABILITY_VALIDATED) &&
netCapabilities.hasBearer(NetCapabilities.BEARER_CELLULAR);
}