1# NetConnection开发指导 2 3## 场景介绍 4 5NetConnection模块提供了常用网络信息查询的能力。 6 7## 接口说明 8 9NetConnection常用接口如下表所示,详细的接口说明请参考[NetConnection](../reference/apis-network-kit/_net_connection.md) 10 11 12| 接口名 | 描述 | 13| -------- | -------- | 14| OH_NetConn_HasDefaultNet(int32_t \*hasDefaultNet) | 检查默认数据网络是否被激活,判断设备是否有网络连接,以便在应用程序中采取相应的措施。 | 15| OH_NetConn_GetDefaultNet(NetConn_NetHandle \*netHandle) | 获得默认激活的数据网络。 | 16| OH_NetConn_IsDefaultNetMetered(int32_t \*isMetered) | 检查当前网络上的数据流量使用是否被计量 | 17| OH_NetConn_GetConnectionProperties(NetConn_NetHandle \*netHandle, NetConn_ConnectionProperties *prop) | 获取netHandle对应的网络的连接信息。 | 18| OH_NetConn_GetNetCapabilities (NetConn_NetHandle \*netHandle, NetConn_NetCapabilities \*netCapacities) | 获取netHandle对应的网络的能力信息。 | 19| OH_NetConn_GetDefaultHttpProxy (NetConn_HttpProxy \*httpProxy) | 获取网络默认的代理配置信息。 如果设置了全局代理,则会返回全局代理配置信息。如果进程已经绑定到指定netHandle对应的网络,则返回网络句柄对应网络的代理配置信息。在其它情况下,将返回默认网络的代理配置信息。 | 20| OH_NetConn_GetAddrInfo (char \*host, char \*serv, struct addrinfo \*hint, struct addrinfo \*\*res, int32_t netId) | 通过netId获取DNS结果。 | 21| OH_NetConn_FreeDnsResult(struct addrinfo \*res) | 释放DNS结果内存。 | 22| OH_NetConn_GetAllNets(NetConn_NetHandleList \*netHandleList) | 获取所有处于连接状态的网络列表。 | 23| OHOS_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | 注册自定义dns解析器。 | 24| OHOS_NetConn_UnregisterDnsResolver(void) | 去注册自定义dns解析器。 | 25 26## 网络管理接口开发示例 27 28### 开发步骤 29 30使用本文档涉及接口获取网络相关信息时,需先创建Native C++工程,在源文件中将相关接口封装,再在ArkTs层对封装的接口进行调用,使用hilog或者console.log等手段选择打印在控制台或者生成设备日志。 31 32本文以实现获取默认激活的数据网络为例,给出具体的开发指导。 33 34### 添加开发依赖 35 36**添加动态链接库** 37 38CMakeLists.txt中添加以下lib: 39 40```txt 41libace_napi.z.so 42libnet_connection.so 43``` 44 45**头文件** 46 47```c 48#include "napi/native_api.h" 49#include "network/netmanager/net_connection.h" 50#include "network/netmanager/net_connection_type.h" 51``` 52 53### 构建工程 54 551、在源文件中编写调用该API的代码,并将结果封装成一个`napi_value`类型的值返回给 Node.js 环境。 56 57```C 58// Get the execution results of the default network connection. 59static napi_value GetDefaultNet(napi_env env, napi_callback_info info) 60{ 61 size_t argc = 1; 62 napi_value args[1] = {nullptr}; 63 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 64 int32_t param; 65 napi_get_value_int32(env, args[0], ¶m); 66 67 NetConn_NetHandle netHandle; 68 if (param== 0) { 69 param= OH_NetConn_GetDefaultNet(NULL); 70 } else { 71 param= OH_NetConn_GetDefaultNet(&netHandle); 72 } 73 74 napi_value result; 75 napi_create_int32(env, param, &result); 76 return result; 77} 78 79// Get the ID of the default network connection. 80static napi_value NetId(napi_env env, napi_callback_info info) { 81 int32_t defaultNetId; 82 83 NetConn_NetHandle netHandle; 84 OH_NetConn_GetDefaultNet(&netHandle); 85 defaultNetId = netHandle.netId; // Get the default netId 86 87 napi_value result; 88 napi_create_int32(env, defaultNetId, &result); 89 90 return result; 91} 92``` 93 94简要说明:这两个函数是用于获取系统默认网络连接的相关信息的。其中,GetDefaultNet是接收ArkTs端传入的测试参数,返回调用接口后对应的返回值,param可以自行调整;如果返回值为0,代表获取成功,401代表参数错误,201代表没有权限;而NetId函数则用于获取默认网络连接的ID。这些信息可以用于进一步的网络操作。 95 96 972、将通过napi封装好的`napi_value`类型对象初始化导出,通过外部函数接口,将以上两个函数暴露给JavaScript使用。 98 99```C 100EXTERN_C_START 101static napi_value Init(napi_env env, napi_value exports) 102{ 103 // Information used to describe an exported attribute. Two properties are defined here: `GetDefaultNet` and `NetId`. 104 napi_property_descriptor desc[] = { 105 {"GetDefaultNet", nullptr, GetDefaultNet, nullptr, nullptr, nullptr, napi_default, nullptr}, 106 {"NetId", nullptr, NetId, nullptr, nullptr, nullptr, napi_default, nullptr}}; 107 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 108 return exports; 109} 110EXTERN_C_END 111``` 112 1133、将上一步中初始化成功的对象通过`RegisterEntryModule`函数,使用`napi_module_register`函数将模块注册到 Node.js 中。 114 115```C 116static napi_module demoModule = { 117 .nm_version = 1, 118 .nm_flags = 0, 119 .nm_filename = nullptr, 120 .nm_register_func = Init, 121 .nm_modname = "entry", 122 .nm_priv = ((void*)0), 123 .reserved = { 0 }, 124}; 125 126extern "C" __attribute__((constructor)) void RegisterEntryModule(void) 127{ 128 napi_module_register(&demoModule); 129} 130``` 131 1324、在工程的index.d.ts文件中定义两个函数的类型。 133 134- GetDefaultNet 函数接受一个数字参数 code,返回一个数字类型的值。 135- NetId 函数不接受参数,返回一个数字类型的值。 136 137```ts 138export const GetDefaultNet: (code: number) => number; 139export const NetId: () => number; 140``` 141 1425、在index.ets文件中对上述封装好的接口进行调用。 143 144```ts 145import testNetManager from 'libentry.so'; 146 147@Entry 148@Component 149struct Index { 150 @State message: string = ''; 151 152 build() { 153 Row() { 154 Column() { 155 Text(this.message) 156 .fontSize(50) 157 .fontWeight(FontWeight.Bold) 158 Button('GetDefaultNet').onClick(event => { 159 this.GetDefaultNet(); 160 }) 161 Button('CodeNumber').onClick(event =>{ 162 this.CodeNumber(); 163 }) 164 } 165 .width('100%') 166 } 167 .height('100%') 168 } 169 170 GetDefaultNet() { 171 let netid = testNetManager.NetId(); 172 console.log("The defaultNetId is [" + netid + "]"); 173 } 174 175 CodeNumber() { 176 let testParam = 0; 177 let codeNumber = testNetManager.GetDefaultNet(testParam); 178 if (codeNumber === 0) { 179 console.log("Test success. [" + codeNumber + "]"); 180 } else if (codeNumber === 201) { 181 console.log("Missing permissions. [" + codeNumber + "]"); 182 } else if (codeNumber === 401) { 183 console.log("Parameter error. [" + codeNumber + "]"); 184 } 185 } 186} 187 188``` 189 1906、配置`CMakeLists.txt`,本模块需要用到的共享库是`libnet_connection.so`,在工程自动生成的`CMakeLists.txt`中的`target_link_libraries`中添加此共享库。 191 192注意:如图所示,在`add_library`中的`entry`是工程自动生成的`modename`,若要做修改,需和步骤3中`.nm_modname`保持一致; 193 194 195 196经过以上步骤,整个工程的搭建已经完成,接下来就可以连接设备运行工程进行日志查看了。 197 198## 测试步骤 199 2001、连接设备,使用DevEco Studio打开搭建好的工程。 201 2022、运行工程,设备上会弹出以下所示图片: 203 204简要说明: 205 206- 在点击 `GetDefaultNet` 时,获取的是默认网络ID。 207- 在点击 `codeNumber` 时,获取的是接口返回的响应状态码。 208 209 210 2113、点击 `GetDefaultNet` 按钮,控制台会打印日志: 212 213 214 2154、点击 `codeNumber` 按钮,控制台会打印相应的响应状态码: 216 217