Network Connection Management provides basic network management capabilities, including priority management for multiple network connections such as Wi-Fi, cellular, and Ethernet, network quality assessment, subscription to default or specified network connection state changes, network connection information queries, and DNS resolution.
To ensure efficient application operation, most APIs are asynchronous. Asynchronous APIs support both callback and promise-based approaches. The examples below use callbacks. For other approaches, see @ohos.net.connection (Network Connection Management).
Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet.
Consumer: a user of data networks, for example, an application or a system service.
Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection.
Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes.
Typical application scenarios of network connection management are as follows:
Querying network connection information based on the data network
Resolving the domain name of a network to obtain all IP addresses
The following describes the development procedure specific to each application scenario.
For details about the complete JS API description and sample code, see @ohos.net.connection (Network Connection Management).
| Name | Description |
|---|---|
| getDefaultNet(callback: AsyncCallback<NetHandle>): void; | Creates a NetHandle object that contains the netId of the default network. This API uses an asynchronous callback to return the result. |
| getDefaultNetSync(): NetHandle; | Obtains the default active data network in synchronous mode. You can use getNetCapabilities to obtain information such as the network type and capabilities. |
| getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback<NetCapabilities>): void; | Obtains the capability set of the default network. This API uses an asynchronous callback to return the result. |
| createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a NetConnection object. netSpecifier specifies the network features, and timeout specifies the timeout interval in ms. timeout is configurable only when netSpecifier is specified. If neither of them is present, the default network is used. |
| on(type: 'netAvailable', callback: Callback<NetHandle>): void; | Subscribes to netAvailable events. |
| on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void; | Subscribes to netCapabilitiesChange events. |
| on(type: 'netLost', callback: Callback<NetHandle>): void; | Subscribes to netLost events. |
| on(type: 'netUnavailable', callback: Callback<void>): void; | Subscribes to netUnavailable events. |
| register(callback: AsyncCallback<void>): void; | Registers an observer for the default network or the network specified in createNetConnection. |
| unregister(callback: AsyncCallback<void>): void; | Unregisters the observer for the default network or the network specified in createNetConnection. |
Declare the required permission: ohos.permission.GET_NETWORK_INFO.
The permission level is normal. Before requesting permissions, ensure that the basic principles for using permissions are met. Then, declare the corresponding permission by referring to Declaring Permissions.
Call createNetConnection() to create a NetConnection object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used.
Call on() to subscribe to the target event. You must pass in type and callback.
Call register() to subscribe to network status changes of the specified network.
When the network is available, the callback will be invoked to return the netAvailable event. When the network is unavailable, the callback will be invoked to return the netUnavailable event.
Call unregister() to unsubscribe from the network status changes if required.
// Import the connection namespace.
import connection from '@ohos.net.connection';
import { BusinessError } from '@kit.BasicServicesKit';
let netSpecifier: connection.NetSpecifier = {
netCapabilities: {
// Assume that the default network is Wi-Fi. If you need to create a cellular network connection, set the network type to **CELLULAR**.
bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// Set the network capability to INTERNET.
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET]
},
};
// Set the timeout value to 10s. The default value is 0.
let timeout = 10 * 1000;
// Create a NetConnection object.
let conn = connection.createNetConnection(netSpecifier, timeout);
// Register an observer for network status changes.
conn.register((err: BusinessError, data: void) => {
console.log(JSON.stringify(err));
});
// Subscribe to network status change events. If the network is available, an on_netAvailable event is returned.
conn.on('netAvailable', ((data: connection.NetHandle) => {
console.log("net is available, netId is " + data.netId);
}));
// Subscribe to network status change events. If the network is unavailable, an on_netUnavailable event is returned.
conn.on('netUnavailable', ((data: void) => {
console.log("net is unavailable, data is " + JSON.stringify(data));
}));
// Call the unregister method to unsubscribe from the network status changes if required.
conn.unregister((err: BusinessError, data: void) => {
}); Declare the required permission: ohos.permission.GET_NETWORK_INFO.
The permission level is normal. Before requesting permissions, ensure that the basic principles for using permissions are met. Then, declare the corresponding permission by referring to Declaring Permissions.
Call getDefaultNet to obtain the default data network via NetHandle or call getAllNets to obtain the list of all connected networks via Array<NetHandle>.
Call getNetCapabilities to obtain the network capability information of the data network specified by NetHandle. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities.
Call getConnectionProperties to obtain the connection information of the data network specified by NetHandle.
import connection from '@ohos.net.connection';
import { BusinessError } from '@kit.BasicServicesKit';
// Construct a singleton object.
export class GlobalContext {
public netList: connection.NetHandle[] = [];
public netHandle: connection.NetHandle|null = null;
private constructor() {}
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
// Call getDefaultNet to obtain the default data network specified by NetHandle.
connection.getDefaultNet((err: BusinessError, data:connection.NetHandle) => {
console.log(JSON.stringify(err));
console.log(JSON.stringify(data));
if (data) {
GlobalContext.getContext().netHandle = data;
}
})
// Obtain the network capability information of the data network specified by NetHandle. The capability information includes information such as the network type and specific network capabilities.
connection.getNetCapabilities(GlobalContext.getContext().netHandle, (err: BusinessError, data: connection.NetCapabilities) => {
console.log(JSON.stringify(err));
// Obtain the network type via bearerTypes.
let bearerTypes: Set<number> = new Set(data.bearerTypes);
let bearerTypesNum = Array.from(bearerTypes.values());
for (let item of bearerTypesNum) {
if (item == 0) {
// Cellular network
console.log(JSON.stringify("BEARER_CELLULAR"));
} else if (item == 1) {
// Wi-Fi network
console.log(JSON.stringify("BEARER_WIFI"));
} else if (item == 3) {
// Ethernet network
console.log(JSON.stringify("BEARER_ETHERNET"));
}
}
// Obtain the specific network capabilities via networkCap.
let itemNumber : Set<number> = new Set([0, 11, 12, 15, 16]);
let dataNumber = Array.from(itemNumber.values());
for (let item of dataNumber) {
if (item == 0) {
// The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.
console.log(JSON.stringify("NET_CAPABILITY_MMS"));
} else if (item == 11) {
// The network traffic is not metered.
console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED"));
} else if (item == 12) {
// The network has the Internet access capability, which is set by the network provider.
console.log(JSON.stringify("NET_CAPABILITY_INTERNET"));
} else if (item == 15) {
// The network does not use a Virtual Private Network (VPN).
console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN"));
} else if (item == 16) {
// The Internet access capability of the network is successfully verified by the connection management module.
console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
}
}
})