In Harmony OS, you can check whether a device is connected to the internet and the type of connection by using the NetManager class. The following is a step-by-step example of how to perform this check:
json{ "module": { "permissions": [ { "name": "ohos.permission.GET_NETWORK_INFO" } ] } }
Next, you can use the NetManager class to retrieve network status and type information. The following is a simple example demonstrating how to write a function to check network connection status and type:
javaimport ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; import ohos.net.NetManager; import ohos.net.NetCapabilities; import ohos.net.NetHandle; import ohos.rpc.RemoteException; public class NetworkCheckAbility extends Ability { @Override public void onStart(Intent intent) { super.onStart(intent); checkNetworkStatus(); } private void checkNetworkStatus() { NetManager netManager = NetManager.getInstance(getContext()); if (netManager == null) { System.out.println("Failed to get NetManager instance."); return; } NetHandle[] netHandles = netManager.getAllNetHandles(); if (netHandles.length == 0) { System.out.println("No active network connections."); return; } try { for (NetHandle handle : netHandles) { NetCapabilities capabilities = netManager.getNetCapabilities(handle); if (capabilities == null) { continue; } if (capabilities.hasCapability(NetCapabilities.NET_CAPABILITY_INTERNET)) { System.out.println("Device is connected to the internet."); if (capabilities.hasTransport(NetCapabilities.TRANSPORT_WIFI)) { System.out.println("Connection type: WiFi"); } else if (capabilities.hasTransport(NetCapabilities.TRANSPORT_CELLULAR)) { System.out.println("Connection type: Cellular"); } else { System.out.println("Connection type: Other/Unknown"); } } } } catch (RemoteException e) { System.out.println("Error checking network capabilities: " + e.getMessage()); } } }
In this example, the NetManager class is used to obtain network handles (NetHandle), each representing a network connection. By using each network handle, you can retrieve a NetCapabilities object, which provides detailed information about the network connection capabilities. By checking for the presence of NET_CAPABILITY_INTERNET and network types (such as WiFi or cellular data), you can determine the device's internet connection status and type.
This check and output help developers effectively manage network status and make appropriate adaptations or notifications within Harmony OS applications.