未验证 提交 75afe266 编写于 作者: O openharmony_ci 提交者: Gitee

!17222 Net Docs Update

Merge pull request !17222 from Yangys/master
...@@ -49,44 +49,43 @@ let httpRequest = http.createHttp(); ...@@ -49,44 +49,43 @@ let httpRequest = http.createHttp();
// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息 // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
httpRequest.request( httpRequest.request(
// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定"EXAMPLE_URL",
"EXAMPLE_URL", {
{ method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET // 开发者根据自身业务需要添加header字段
// 开发者根据自身业务需要添加header字段 header: {
header: { 'Content-Type': 'application/json'
'Content-Type': 'application/json' },
}, // 当使用POST请求时此字段用于传递内容
// 当使用POST请求时此字段用于传递内容 extraData: {
extraData: { "data": "data to send",
"data": "data to send", },
}, expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 usingCache: true, // 可选,默认为true
usingCache: true, // 可选,默认为true priority: 1, // 可选,默认为1
priority: 1, // 可选,默认为1 connectTimeout: 60000, // 可选,默认为60000ms
connectTimeout: 60000, // 可选,默认为60000ms readTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性
usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性 }, (err, data) => {
}, (err, data) => { if (!err) {
if (!err) { // data.result为HTTP响应内容,可根据业务需要进行解析
// data.result为HTTP响应内容,可根据业务需要进行解析 console.info('Result:' + JSON.stringify(data.result));
console.info('Result:' + JSON.stringify(data.result)); console.info('code:' + JSON.stringify(data.responseCode));
console.info('code:' + JSON.stringify(data.responseCode)); // data.header为HTTP响应头,可根据业务需要进行解析
// data.header为HTTP响应头,可根据业务需要进行解析 console.info('header:' + JSON.stringify(data.header));
console.info('header:' + JSON.stringify(data.header)); console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ } else {
} else { console.info('error:' + JSON.stringify(err));
console.info('error:' + JSON.stringify(err)); // 取消订阅HTTP响应头事件
// 取消订阅HTTP响应头事件 httpRequest.off('headersReceive');
httpRequest.off('headersReceive'); // 当该请求使用完毕时,调用destroy方法主动销毁
// 当该请求使用完毕时,调用destroy方法主动销毁 httpRequest.destroy();
httpRequest.destroy();
}
} }
}
); );
``` ```
...@@ -108,61 +107,63 @@ import http from '@ohos.net.http' ...@@ -108,61 +107,63 @@ import http from '@ohos.net.http'
let httpRequest = http.createHttp(); let httpRequest = http.createHttp();
// 用于订阅HTTP响应头事件 // 用于订阅HTTP响应头事件
httpRequest.on('headersReceive', (header) => { httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header)); console.info('header: ' + JSON.stringify(header));
}); });
// 用于订阅HTTP流式响应数据接收事件 // 用于订阅HTTP流式响应数据接收事件
let res = ''; let res = '';
httpRequest.on('dataReceive', (data) => { httpRequest.on('dataReceive', (data) => {
res += data; res += data;
console.info('res: ' + res); console.info('res: ' + res);
}); });
// 用于订阅HTTP流式响应数据接收完毕事件 // 用于订阅HTTP流式响应数据接收完毕事件
httpRequest.on('dataEnd', () => { httpRequest.on('dataEnd', () => {
console.info('No more data in response, data receive end'); console.info('No more data in response, data receive end');
}); });
// 用于订阅HTTP流式响应数据接收进度事件 // 用于订阅HTTP流式响应数据接收进度事件
httpRequest.on('dataProgress', (data) => { httpRequest.on('dataProgress', (data) => {
console.log("dataProgress receiveSize:" + data.receiveSize+ ", totalSize:" + data.totalSize); console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
}); });
httpRequest.request2( httpRequest.request2(
// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
// 开发者根据自身业务需要添加header字段 // 开发者根据自身业务需要添加header字段
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
// 当使用POST请求时此字段用于传递内容 // 当使用POST请求时此字段用于传递内容
extraData: { extraData: {
"data": "data to send", "data": "data to send",
}, },
expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
usingCache: true, // 可选,默认为true usingCache: true, // 可选,默认为true
priority: 1, // 可选,默认为1 priority: 1, // 可选,默认为1
connectTimeout: 60000, // 可选,默认为60000ms connectTimeout: 60000, // 可选,默认为60000ms
readTimeout: 60000, // 可选,默认为60000ms。若传输的数据较大,需要较长的时间,建议增大该参数以保证数据传输正常终止 readTimeout: 60000, // 可选,默认为60000ms。若传输的数据较大,需要较长的时间,建议增大该参数以保证数据传输正常终止
usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
}, (err, data) => { }, (err, data) => {
console.info('error:' + JSON.stringify(err)); console.info('error:' + JSON.stringify(err));
console.info('ResponseCode :' + JSON.stringify(data)); console.info('ResponseCode :' + JSON.stringify(data));
// 取消订阅HTTP响应头事件 // 取消订阅HTTP响应头事件
httpRequest.off('headersReceive'); httpRequest.off('headersReceive');
// 取消订阅HTTP流式响应数据接收事件 // 取消订阅HTTP流式响应数据接收事件
httpRequest.off('dataReceive'); httpRequest.off('dataReceive');
// 取消订阅HTTP流式响应数据接收进度事件 // 取消订阅HTTP流式响应数据接收进度事件
httpRequest.off('dataProgress'); httpRequest.off('dataProgress');
// 取消订阅HTTP流式响应数据接收完毕事件 // 取消订阅HTTP流式响应数据接收完毕事件
httpRequest.off('dataEnd'); httpRequest.off('dataEnd');
// 当该请求使用完毕时,调用destroy方法主动销毁 // 当该请求使用完毕时,调用destroy方法主动销毁
httpRequest.destroy(); httpRequest.destroy();
} }
); );
``` ```
## 相关实例 ## 相关实例
针对HTTP数据请求,有以下相关实例可供参考: 针对HTTP数据请求,有以下相关实例可供参考:
- [`Http:`数据请求(ArkTS)(API9))](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http) - [`Http:`数据请求(ArkTS)(API9))](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [使用HTTP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) - [使用HTTP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
\ No newline at end of file
# 网络连接管理 # 网络连接管理
## 简介 ## 简介
网络连接管理提供管理网络一些基础能力,包括WiFi/蜂窝/Ethernet等多网络连接优先级管理、网络质量评估、订阅默认/指定网络连接状态变化、查询网络连接信息、DNS解析等功能。 网络连接管理提供管理网络一些基础能力,包括WiFi/蜂窝/Ethernet等多网络连接优先级管理、网络质量评估、订阅默认/指定网络连接状态变化、查询网络连接信息、DNS解析等功能。
> **说明:** > **说明:**
> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-connection.md)。 > 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-connection.md)。
## 基本概念 ## 基本概念
- 网络生产者:数据网络的提供方,比如WiFi、蜂窝、Ethernet等。
- 网络消费者:数据网络的使用方,比如应用或系统服务。 - 网络生产者:数据网络的提供方,比如WiFi、蜂窝、Ethernet等。
- 网络探测:检测网络有效性,避免将网络从可用网络切换到不可用网络。内容包括绑定网络探测、DNS探测、HTTP探测及HTTPS探测。 - 网络消费者:数据网络的使用方,比如应用或系统服务。
- 网络优选:处理多网络共存时选择最优网络。在网络状态、网络信息及评分发生变化时被触发。 - 网络探测:检测网络有效性,避免将网络从可用网络切换到不可用网络。内容包括绑定网络探测、DNS探测、HTTP探测及HTTPS探测。
- 网络优选:处理多网络共存时选择最优网络。在网络状态、网络信息及评分发生变化时被触发。
## 约束 ## 约束
- 开发语言:C++ JS
- 系统:linux内核 - 开发语言:C++ JS
- 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - 系统:linux内核
- 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 场景介绍 ## 场景介绍
网络连接管理的典型场景有: 网络连接管理的典型场景有:
- 接收指定网络的状态变化通知
- 获取所有注册的网络 - 接收指定网络的状态变化通知
- 根据数据网络查询网络的连接信息 - 获取所有注册的网络
- 使用对应网络解析域名,获取所有IP - 根据数据网络查询网络的连接信息
- 使用对应网络解析域名,获取所有IP
以下分别介绍具体开发方式。 以下分别介绍具体开发方式。
## 接口说明 ## 接口说明
完整的JS API说明以及实例代码请参考:[网络连接管理](../reference/apis/js-apis-net-connection.md) 完整的JS API说明以及实例代码请参考:[网络连接管理](../reference/apis/js-apis-net-connection.md)
| 类型 | 接口 | 功能说明 | | 类型 | 接口 | 功能说明 |
...@@ -75,44 +82,46 @@ ...@@ -75,44 +82,46 @@
```js ```js
// 引入包名 // 引入包名
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
let netCap = { let netCap = {
// 假设当前默认网络是WiFi,需要创建蜂窝网络连接,可指定网络类型为蜂窝网 // 假设当前默认网络是WiFi,需要创建蜂窝网络连接,可指定网络类型为蜂窝网
bearerTypes: [connection.NetBearType.BEARER_CELLULAR], bearerTypes: [connection.NetBearType.BEARER_CELLULAR],
// 指定网络能力为Internet // 指定网络能力为Internet
networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET],
}; };
let netSpec = { let netSpec = {
netCapabilities: netCap, netCapabilities: netCap,
}; };
// 指定超时时间为10s(默认值为0) // 指定超时时间为10s(默认值为0)
let timeout = 10 * 1000; let timeout = 10 * 1000;
// 创建NetConnection对象 // 创建NetConnection对象
let conn = connection.createNetConnection(netSpec, timeout); let conn = connection.createNetConnection(netSpec, timeout);
// 订阅事件,如果当前指定网络可用,通过on_netAvailable通知用户 // 订阅事件,如果当前指定网络可用,通过on_netAvailable通知用户
conn.on('netAvailable', (data=> { conn.on('netAvailable', (data => {
console.log("net is available, netId is " + data.netId); console.log("net is available, netId is " + data.netId);
})); }));
// 订阅事件,如果当前指定网络不可用,通过on_netUnavailable通知用户 // 订阅事件,如果当前指定网络不可用,通过on_netUnavailable通知用户
conn.on('netUnavailable', (data=> { conn.on('netUnavailable', (data => {
console.log("net is unavailable, netId is " + data.netId); console.log("net is unavailable, netId is " + data.netId);
})); }));
// 订阅指定网络状态变化的通知 // 订阅指定网络状态变化的通知
conn.register((err, data) => {}); conn.register((err, data) => {
});
// 当不使用该网络时,可以调用该对象的unregister()方法,取消订阅
conn.unregister((err, data) => {}); // 当不使用该网络时,可以调用该对象的unregister()方法,取消订阅
conn.unregister((err, data) => {
});
``` ```
## 获取所有注册的网络 ## 获取所有注册的网络
### 开发步骤 ### 开发步骤
1. 从@ohos.net.connection.d.ts中导入connection命名空间。 1. 从@ohos.net.connection.d.ts中导入connection命名空间。
...@@ -120,21 +129,21 @@ ...@@ -120,21 +129,21 @@
```js ```js
// 引入包名 // 引入包名
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// 获取所有处于连接状态的网络列表 // 获取所有处于连接状态的网络列表
connection.getAllNets((err, data) => { connection.getAllNets((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netList = data; this.netList = data;
} }
}) })
``` ```
## 根据数据网络查询网络的能力信息及连接信息 ## 根据数据网络查询网络的能力信息及连接信息
### 开发步骤 ### 开发步骤
1. 从@ohos.net.connection.d.ts中导入connection命名空间。 1. 从@ohos.net.connection.d.ts中导入connection命名空间。
...@@ -146,89 +155,89 @@ ...@@ -146,89 +155,89 @@
```js ```js
// 引入包名 // 引入包名
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// 调用getDefaultNet方法,获取默认的数据网络(NetHandle) // 调用getDefaultNet方法,获取默认的数据网络(NetHandle)
connection.getDefaultNet((err, data) => { connection.getDefaultNet((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netHandle = data; this.netHandle = data;
} }
}) })
// 获取netHandle对应网络的能力信息。能力信息包含了网络类型、网络具体能力等网络信息 // 获取netHandle对应网络的能力信息。能力信息包含了网络类型、网络具体能力等网络信息
connection.getNetCapabilities(this.netHandle, (err, data) => { connection.getNetCapabilities(this.netHandle, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
// 获取网络类型(bearerTypes) // 获取网络类型(bearerTypes)
for (let item of data.bearerTypes) { for (let item of data.bearerTypes) {
if (item == 0) { if (item == 0) {
// 蜂窝网 // 蜂窝网
console.log(JSON.stringify("BEARER_CELLULAR")); console.log(JSON.stringify("BEARER_CELLULAR"));
} else if (item == 1) { } else if (item == 1) {
// Wi-Fi网络 // Wi-Fi网络
console.log(JSON.stringify("BEARER_WIFI")); console.log(JSON.stringify("BEARER_WIFI"));
} else if (item == 3) { } else if (item == 3) {
// 以太网网络 // 以太网网络
console.log(JSON.stringify("BEARER_ETHERNET")); console.log(JSON.stringify("BEARER_ETHERNET"));
} }
} }
// 获取网络具体能力(networkCap) // 获取网络具体能力(networkCap)
for (let item of data.networkCap) { for (let item of data.networkCap) {
if (item == 0) { if (item == 0) {
// 表示网络可以访问运营商的MMSC(Multimedia Message Service,多媒体短信服务)发送和接收彩信 // 表示网络可以访问运营商的MMSC(Multimedia Message Service,多媒体短信服务)发送和接收彩信
console.log(JSON.stringify("NET_CAPABILITY_MMS")); console.log(JSON.stringify("NET_CAPABILITY_MMS"));
} else if (item == 11) { } else if (item == 11) {
// 表示网络流量未被计费 // 表示网络流量未被计费
console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED")); console.log(JSON.stringify("NET_CAPABILITY_NOT_METERED"));
} else if (item == 12) { } else if (item == 12) {
// 表示该网络应具有访问Internet的能力,该能力由网络提供者设置 // 表示该网络应具有访问Internet的能力,该能力由网络提供者设置
console.log(JSON.stringify("NET_CAPABILITY_INTERNET")); console.log(JSON.stringify("NET_CAPABILITY_INTERNET"));
} else if (item == 15) { } else if (item == 15) {
// 表示网络不使用VPN(Virtual Private Network,虚拟专用网络) // 表示网络不使用VPN(Virtual Private Network,虚拟专用网络)
console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN")); console.log(JSON.stringify("NET_CAPABILITY_NOT_VPN"));
} else if (item == 16) { } else if (item == 16) {
// 表示该网络访问Internet的能力被网络管理成功验证,该能力由网络管理模块设置 // 表示该网络访问Internet的能力被网络管理成功验证,该能力由网络管理模块设置
console.log(JSON.stringify("NET_CAPABILITY_VALIDATED")); console.log(JSON.stringify("NET_CAPABILITY_VALIDATED"));
} }
} }
}) })
// 获取netHandle对应网络的连接信息。连接信息包含了链路信息、路由信息等 // 获取netHandle对应网络的连接信息。连接信息包含了链路信息、路由信息等
connection.getConnectionProperties(this.netHandle, (err, data) => { connection.getConnectionProperties(this.netHandle, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
// 调用getAllNets,获取所有处于连接状态的网络列表(Array<NetHandle>) // 调用getAllNets,获取所有处于连接状态的网络列表(Array<NetHandle>)
connection.getAllNets((err, data) => { connection.getAllNets((err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
if (data) { if (data) {
this.netList = data; this.netList = data;
} }
}) })
for (let item of this.netList) { for (let item of this.netList) {
// 循环获取网络列表每个netHandle对应网络的能力信息 // 循环获取网络列表每个netHandle对应网络的能力信息
connection.getNetCapabilities(item, (err, data) => { connection.getNetCapabilities(item, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
// 循环获取网络列表每个netHandle对应的网络的连接信息 // 循环获取网络列表每个netHandle对应的网络的连接信息
connection.getConnectionProperties(item, (err, data) => { connection.getConnectionProperties(item, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
} }
``` ```
## 使用对应网络解析域名,获取所有IP ## 使用对应网络解析域名,获取所有IP
### 开发步骤 ### 开发步骤
1. 从@ohos.net.connection.d.ts中导入connection命名空间。 1. 从@ohos.net.connection.d.ts中导入connection命名空间。
...@@ -236,11 +245,11 @@ ...@@ -236,11 +245,11 @@
```js ```js
// 引入包名 // 引入包名
import connection from '@ohos.net.connection' import connection from '@ohos.net.connection'
// 使用默认网络解析主机名以获取所有IP地址 // 使用默认网络解析主机名以获取所有IP地址
connection.getAddressesByName(this.host, (err, data) => { connection.getAddressesByName(this.host, (err, data) => {
console.log(JSON.stringify(err)); console.log(JSON.stringify(err));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
``` ```
# 以太网连接 # 以太网连接
## 简介 ## 简介
以太网连接的功能是提供支持设备通过硬件接口,以插入网线的形式访问互联网的能力。
设备接入网线后,可以获取动态分配的IP地址,子网掩码,Gateway,DNS等一系列网络属性;通过静态模式,手动配置与获取设备的网络属性。 以太网连接的功能是提供支持设备通过硬件接口,以插入网线的形式访问互联网的能力。 设备接入网线后,可以获取动态分配的IP地址,子网掩码,Gateway,DNS等一系列网络属性;通过静态模式,手动配置与获取设备的网络属性。
> **说明:** > **说明:**
> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-ethernet.md)。 > 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-ethernet.md)。
## 约束 ## 约束
- 开发语言:C++ JS
- 系统:linux内核 - 开发语言:C++ JS
- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - 系统:linux内核
- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 场景介绍 ## 场景介绍
以太网连接的典型场景有: 以太网连接的典型场景有:
- DHCP模式,通过动态分配IP地址,子网掩码,Gateway,DNS等一系列网络属性,使能访问网络。
- 静态模式,通过静态配置IP地址,子网掩码,Gateway,DNS等一系列网络属性,使能访问网络。 - DHCP模式,通过动态分配IP地址,子网掩码,Gateway,DNS等一系列网络属性,使能访问网络。
- 静态模式,通过静态配置IP地址,子网掩码,Gateway,DNS等一系列网络属性,使能访问网络。
以下分别介绍具体开发方式。 以下分别介绍具体开发方式。
## 接口说明 ## 接口说明
完整的JS API说明以及实例代码请参考:[以太网连接](../reference/apis/js-apis-net-ethernet.md) 完整的JS API说明以及实例代码请参考:[以太网连接](../reference/apis/js-apis-net-ethernet.md)
| 类型 | 接口 | 功能说明 | | 类型 | 接口 | 功能说明 |
...@@ -28,6 +32,8 @@ ...@@ -28,6 +32,8 @@
| ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void | 获取指定以太网的网络属性,iface为网口名称,调用callback | | ohos.net.ethernet | function getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void | 获取指定以太网的网络属性,iface为网口名称,调用callback |
| ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\<number>): void | 判断指定网口是否已激活,iface为网卡名称(无参为是否有激活网口),调用callback | | ohos.net.ethernet | function isIfaceActive(iface: string, callback: AsyncCallback\<number>): void | 判断指定网口是否已激活,iface为网卡名称(无参为是否有激活网口),调用callback |
| ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void; | 获取所有活动的网络接口,调用callback | | ohos.net.ethernet | function getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void; | 获取所有活动的网络接口,调用callback |
| ohos.net.ethernet | function on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void; | 注册网络接口监听函数 |
| ohos.net.ethernet | function off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void; | 解除注册网络接口监听函数 |
## 以太网连接-DHCP模式 ## 以太网连接-DHCP模式
...@@ -39,44 +45,45 @@ ...@@ -39,44 +45,45 @@
```js ```js
// 从@ohos.net.ethernet中导入ethernet命名空间 // 从@ohos.net.ethernet中导入ethernet命名空间
import ethernet from '@ohos.net.ethernet' import ethernet from '@ohos.net.ethernet'
// getAllActiveIfaces获取所有活动的网络设备名称 // getAllActiveIfaces获取所有活动的网络设备名称
ethernet.getAllActiveIfaces((error, data) => { ethernet.getAllActiveIfaces((error, data) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + error);
} else { } else {
console.log("getAllActiveIfaces callback data.length = " + data.length); console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]); console.log("getAllActiveIfaces callback = " + data[i]);
} }
} }
}); });
// isIfaceActive判断指定网口是否已激活 // isIfaceActive判断指定网口是否已激活
ethernet.isIfaceActive("eth0", (error, data) => { ethernet.isIfaceActive("eth0", (error, data) => {
if (error) { if (error) {
console.log("isIfaceActive callback error = " + error); console.log("isIfaceActive callback error = " + error);
} else { } else {
console.log("isIfaceActive callback = " + data); console.log("isIfaceActive callback = " + data);
} }
}); });
// getIfaceConfig获取指定以太网的网络属性 // getIfaceConfig获取指定以太网的网络属性
ethernet.getIfaceConfig("eth0", (error, data) => { ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + error); console.log("getIfaceConfig callback error = " + error);
} else { } else {
console.log("getIfaceConfig callback mode = " + data.mode); console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
} }
}); });
``` ```
## 以太网连接-静态模式 ## 以太网连接-静态模式
### 开发步骤 ### 开发步骤
...@@ -90,51 +97,75 @@ ...@@ -90,51 +97,75 @@
```js ```js
// 从@ohos.net.ethernet中导入ethernet命名空间 // 从@ohos.net.ethernet中导入ethernet命名空间
import ethernet from '@ohos.net.ethernet' import ethernet from '@ohos.net.ethernet'
// getAllActiveIfaces获取所有活动的网络设备名称 // getAllActiveIfaces获取所有活动的网络设备名称
ethernet.getAllActiveIfaces((error, data) => { ethernet.getAllActiveIfaces((error, data) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + error); console.log("getAllActiveIfaces callback error = " + error);
} else { } else {
console.log("getAllActiveIfaces callback data.length = " + data.length); console.log("getAllActiveIfaces callback data.length = " + data.length);
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces callback = " + data[i]); console.log("getAllActiveIfaces callback = " + data[i]);
} }
} }
}); });
// isIfaceActive判断指定网口是否已激活 // isIfaceActive判断指定网口是否已激活
ethernet.isIfaceActive("eth0", (error, data) => { ethernet.isIfaceActive("eth0", (error, data) => {
if (error) { if (error) {
console.log("isIfaceActive callback error = " + error); console.log("isIfaceActive callback error = " + error);
} else { } else {
console.log("isIfaceActive callback = " + data); console.log("isIfaceActive callback = " + data);
} }
}); });
// setIfaceConfig配置指定以太网的网络属性 // setIfaceConfig配置指定以太网的网络属性
ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.xx.xx", routeAddr:"192.168.xx.xx", ethernet.setIfaceConfig("eth0", {
gateAddr:"192.168.xx.xx", maskAddr:"255.255.xx.xx", dnsAddr0:"1.1.xx.xx", dnsAddr1:"2.2.xx.xx"},(error) => { mode: ethernet.STATIC, ipAddr: "192.168.xx.xx", routeAddr: "192.168.xx.xx",
if (error) { gateAddr: "192.168.xx.xx", maskAddr: "255.255.xx.xx", dnsAddr0: "1.1.xx.xx", dnsAddr1: "2.2.xx.xx"
console.log("setIfaceConfig callback error = " + error); }, (error) => {
} else { if (error) {
console.log("setIfaceConfig callback ok "); console.log("setIfaceConfig callback error = " + error);
} } else {
}); console.log("setIfaceConfig callback ok ");
}
// getIfaceConfig获取指定以太网的网络属性 });
ethernet.getIfaceConfig("eth0", (error, data) => {
if (error) { // getIfaceConfig获取指定以太网的网络属性
console.log("getIfaceConfig callback error = " + error); ethernet.getIfaceConfig("eth0", (error, data) => {
} else { if (error) {
console.log("getIfaceConfig callback mode = " + data.mode); console.log("getIfaceConfig callback error = " + error);
console.log("getIfaceConfig callback ipAddr = " + data.ipAddr); } else {
console.log("getIfaceConfig callback routeAddr = " + data.routeAddr); console.log("getIfaceConfig callback mode = " + data.mode);
console.log("getIfaceConfig callback gateAddr = " + data.gateAddr); console.log("getIfaceConfig callback ipAddr = " + data.ipAddr);
console.log("getIfaceConfig callback maskAddr = " + data.maskAddr); console.log("getIfaceConfig callback routeAddr = " + data.routeAddr);
console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr); console.log("getIfaceConfig callback gateAddr = " + data.gateAddr);
console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr); console.log("getIfaceConfig callback maskAddr = " + data.maskAddr);
} console.log("getIfaceConfig callback dns0Addr = " + data.dns0Addr);
}); console.log("getIfaceConfig callback dns1Addr = " + data.dns1Addr);
}
});
``` ```
## 监听网络设备接口状态变化
### 开发步骤
1. 从@ohos.net.ethernet中导入ethernet命名空间。
2. 调用该对象的on()方法,订阅interfaceStateChange事件。可以根据业务需要订阅此消息。
3. 订阅interfaceStateChange事件后,回调函数会在网卡设备的接口状态发生变化时触发。
4. 调用该对象的off()方法,取消订阅interfaceStateChange事件。
```js
// 从@ohos.net.ethernet中导入ethernet命名空间
import ethernet from '@ohos.net.ethernet'
// 订阅interfaceStateChange事件
ethernet.on('interfaceStateChange', ((data) => {
console.log(JSON.stringify(data));
}));
// 取消事件订阅
ethernet.off('interfaceStateChange');
```
\ No newline at end of file
# 网络共享 # 网络共享
## 简介 ## 简介
网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。 网络共享管理分享设备已有网络给其他连接设备,支持Wi-Fi热点共享、蓝牙共享和USB共享,同时提供网络共享状态、共享流量查询功能。
> **说明:** > **说明:**
> 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-sharing.md)。 > 为了保证应用的运行效率,大部分API调用都是异步的,对于异步调用的API均提供了callback和Promise两种方式,以下示例均采用callback函数,更多方式可以查阅[API参考](../reference/apis/js-apis-net-sharing.md)。
## 基本概念 ## 基本概念
- WIFI共享:通过WIFI热点共享网络。
- 蓝牙共享:通过蓝牙共享网络。 - WIFI共享:通过WIFI热点共享网络。
- USB共享:通过USB共享网络。 - 蓝牙共享:通过蓝牙共享网络。
- USB共享:通过USB共享网络。
## 约束 ## 约束
- 开发语言:C++ JS
- 系统:linux内核 - 开发语言:C++ JS
- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - 系统:linux内核
- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 场景介绍 ## 场景介绍
网络共享的典型场景有: 网络共享的典型场景有:
- 开启网络共享
- 停止网络共享 - 开启网络共享
- 获取共享网络的数据流量 - 停止网络共享
- 获取共享网络的数据流量
以下分别介绍具体开发方式。 以下分别介绍具体开发方式。
## 接口说明 ## 接口说明
完整的JS API说明以及实例代码请参考:[网络共享](../reference/apis/js-apis-net-sharing.md) 完整的JS API说明以及实例代码请参考:[网络共享](../reference/apis/js-apis-net-sharing.md)
| 类型 | 接口 | 功能说明 | | 类型 | 接口 | 功能说明 |
...@@ -54,18 +61,18 @@ ...@@ -54,18 +61,18 @@
```js ```js
// 从@ohos.net.sharing中导入sharing命名空间 // 从@ohos.net.sharing中导入sharing命名空间
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// 注册监听共享状态的改变 // 注册监听共享状态的改变
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// 调用startSharing方法,来开启指定类型共享 // 调用startSharing方法,来开启指定类型共享
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## 停止网络共享 ## 停止网络共享
...@@ -79,18 +86,18 @@ ...@@ -79,18 +86,18 @@
```js ```js
// 从@ohos.net.sharing中导入sharing命名空间 // 从@ohos.net.sharing中导入sharing命名空间
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// 注册监听共享状态的改变 // 注册监听共享状态的改变
sharing.on('sharingStateChange', (error, data) => { sharing.on('sharingStateChange', (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// 调用stopSharing方法,来停止指定类型共享 // 调用stopSharing方法,来停止指定类型共享
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
## 获取共享网络的数据流量 ## 获取共享网络的数据流量
...@@ -104,27 +111,27 @@ ...@@ -104,27 +111,27 @@
```js ```js
// 从@ohos.net.sharing中导入sharing命名空间 // 从@ohos.net.sharing中导入sharing命名空间
import sharing from '@ohos.net.sharing' import sharing from '@ohos.net.sharing'
// 调用startSharing方法,来开启指定类型共享 // 调用startSharing方法,来开启指定类型共享
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// 调用getStatsTotalBytes方法,来获取共享网络数据量 // 调用getStatsTotalBytes方法,来获取共享网络数据量
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
// 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零 // 调用stopSharing方法,来停止指定类型共享,共享网络数据量清零
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => { sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
// 再次调用getStatsTotalBytes方法,共享网络数据量已清零 // 再次调用getStatsTotalBytes方法,共享网络数据量已清零
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -186,143 +186,144 @@ UDP与TCP流程大体类似,下面以TCP为例: ...@@ -186,143 +186,144 @@ UDP与TCP流程大体类似,下面以TCP为例:
```js ```js
import socket from '@ohos.net.socket' import socket from '@ohos.net.socket'
// 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。 // 创建一个(双向认证)TLS Socket连接,返回一个TLS Socket对象。
let tlsTwoWay = socket.constructTLSSocketInstance(); let tlsTwoWay = socket.constructTLSSocketInstance();
// 订阅TLS Socket相关的订阅事件 // 订阅TLS Socket相关的订阅事件
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
let str = "" let str = ""
for (let i = 0; i < dataView.byteLength; ++i) { for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// 绑定本地IP地址和端口。 // 绑定本地IP地址和端口。
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// 设置通信过程中使用参数 // 设置通信过程中使用参数
let options = { let options = {
ALPNProtocols: ["spdy/1", "http/1.1"], ALPNProtocols: ["spdy/1", "http/1.1"],
// 连接到指定的IP地址和端口。 // 连接到指定的IP地址和端口。
address: { address: {
address: "192.168.xx.xxx", address: "192.168.xx.xxx",
port: xxxx, // 端口 port: xxxx, // 端口
family: 1, family: 1,
}, },
// 设置用于通信过程中完成校验的参数。 // 设置用于通信过程中完成校验的参数。
secureOptions: { secureOptions: {
key: "xxxx", // 密钥 key: "xxxx", // 密钥
cert: "xxxx", // 数字证书 cert: "xxxx", // 数字证书
ca: ["xxxx"], // CA证书 ca: ["xxxx"], // CA证书
passwd: "xxxx", // 生成密钥时的密码 passwd: "xxxx", // 生成密钥时的密码
protocols: [socket.Protocol.TLSv12], // 通信协议 protocols: [socket.Protocol.TLSv12], // 通信协议
useRemoteCipherPrefer: true, // 是否优先使用对端密码套件 useRemoteCipherPrefer: true, // 是否优先使用对端密码套件
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // 签名算法 signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // 签名算法
cipherSuite: "AES256-SHA256", // 密码套件 cipherSuite: "AES256-SHA256", // 密码套件
}, },
}; };
// 建立连接 // 建立连接
tlsTwoWay.connect(options, (err, data) => { tlsTwoWay.connect(options, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// 连接使用完毕后,主动关闭。取消相关事件的订阅。 // 连接使用完毕后,主动关闭。取消相关事件的订阅。
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
// 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。 // 创建一个(单向认证)TLS Socket连接,返回一个TLS Socket对象。
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// 订阅TLS Socket相关的订阅事件 // 订阅TLS Socket相关的订阅事件
tlsTwoWay.on('message', value => { tlsTwoWay.on('message', value => {
console.log("on message") console.log("on message")
let buffer = value.message let buffer = value.message
let dataView = new DataView(buffer) let dataView = new DataView(buffer)
let str = "" let str = ""
for (let i = 0;i < dataView.byteLength; ++i) { for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i)) str += String.fromCharCode(dataView.getUint8(i))
} }
console.log("on connect received:" + str) console.log("on connect received:" + str)
}); });
tlsTwoWay.on('connect', () => { tlsTwoWay.on('connect', () => {
console.log("on connect") console.log("on connect")
}); });
tlsTwoWay.on('close', () => { tlsTwoWay.on('close', () => {
console.log("on close") console.log("on close")
}); });
// 绑定本地IP地址和端口。 // 绑定本地IP地址和端口。
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) { if (err) {
console.log('bind fail'); console.log('bind fail');
return; return;
} }
console.log('bind success'); console.log('bind success');
}); });
// 设置通信过程中使用参数 // 设置通信过程中使用参数
let oneWayOptions = { let oneWayOptions = {
address: { address: {
address: "192.168.xxx.xxx", address: "192.168.xxx.xxx",
port: xxxx, port: xxxx,
family: 1, family: 1,
}, },
secureOptions: { secureOptions: {
ca: ["xxxx","xxxx"], // CA证书 ca: ["xxxx", "xxxx"], // CA证书
cipherSuite: "AES256-SHA256", // 密码套件 cipherSuite: "AES256-SHA256", // 密码套件
}, },
}; };
// 建立连接 // 建立连接
tlsOneWay.connect(oneWayOptions, (err, data) => { tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err); console.error(err);
console.log(data); console.log(data);
}); });
// 连接使用完毕后,主动关闭。取消相关事件的订阅。 // 连接使用完毕后,主动关闭。取消相关事件的订阅。
tlsTwoWay.close((err) => { tlsTwoWay.close((err) => {
if (err) { if (err) {
console.log("close callback error = " + err); console.log("close callback error = " + err);
} else { } else {
console.log("close success"); console.log("close success");
} }
tlsTwoWay.off('message'); tlsTwoWay.off('message');
tlsTwoWay.off('connect'); tlsTwoWay.off('connect');
tlsTwoWay.off('close'); tlsTwoWay.off('close');
}); });
``` ```
## 相关实例 ## 相关实例
针对Socket连接开发,有以下相关实例可供参考: 针对Socket连接开发,有以下相关实例可供参考:
- [`Socket`:Socket 连接(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) - [`Socket`:Socket 连接(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket)
- [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) - [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH)
- [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) - [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo)
# WebSocket连接 # WebSocket连接
## 场景介绍 ## 场景介绍
使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket()方法创建WebSocket对象,然后通过connect()方法连接到服务器。当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send()方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close()方法主动断开连接,之后客户端会收到close事件的回调。 使用WebSocket建立服务器与客户端的双向连接,需要先通过createWebSocket()方法创建WebSocket对象,然后通过connect()方法连接到服务器。当连接成功后,客户端会收到open事件的回调,之后客户端就可以通过send()方法与服务器进行通信。当服务器发信息给客户端时,客户端会收到message事件的回调。当客户端不要此连接时,可以通过调用close()方法主动断开连接,之后客户端会收到close事件的回调。
若在上述任一过程中发生错误,客户端会收到error事件的回调。 若在上述任一过程中发生错误,客户端会收到error事件的回调。
## 接口说明 ## 接口说明
WebSocket连接功能主要由webSocket模块提供。使用该功能需要申请ohos.permission.INTERNET权限。具体接口说明如下表。 WebSocket连接功能主要由webSocket模块提供。使用该功能需要申请ohos.permission.INTERNET权限。具体接口说明如下表。
...@@ -27,7 +25,6 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ...@@ -27,7 +25,6 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申
| on(type: 'error') | 订阅WebSocket的Error事件。 | | on(type: 'error') | 订阅WebSocket的Error事件。 |
| off(type: 'error') | 取消订阅WebSocket的Error事件。 | | off(type: 'error') | 取消订阅WebSocket的Error事件。 |
## 开发步骤 ## 开发步骤
1. 导入需要的webSocket模块。 1. 导入需要的webSocket模块。
...@@ -39,7 +36,7 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ...@@ -39,7 +36,7 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申
4. 根据URL地址,发起WebSocket连接。 4. 根据URL地址,发起WebSocket连接。
5. 使用完WebSocket连接之后,主动断开连接。 5. 使用完WebSocket连接之后,主动断开连接。
```js ```js
import webSocket from '@ohos.net.webSocket'; import webSocket from '@ohos.net.webSocket';
...@@ -87,4 +84,5 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ...@@ -87,4 +84,5 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申
## 相关实例 ## 相关实例
针对WebSocket连接的开发,有以下相关实例可供参考: 针对WebSocket连接的开发,有以下相关实例可供参考:
- [`WebSocket`:WebSocket(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/WebSocket) - [`WebSocket`:WebSocket(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/WebSocket)
\ No newline at end of file
...@@ -48,19 +48,19 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac ...@@ -48,19 +48,19 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallbac
```js ```js
ethernet.setIfaceConfig("eth0", { ethernet.setIfaceConfig("eth0", {
mode: 0, mode: 0,
ipAddr: "192.168.xx.xxx", ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx", route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx", gateway: "192.168.xx.xxx",
netMask: "255.255.255.0", netMask: "255.255.255.0",
dnsServers: "1.1.1.1", dnsServers: "1.1.1.1",
domain: "2.2.2.2" domain: "2.2.2.2"
}, (error) => { }, (error) => {
if (error) { if (error) {
console.log("setIfaceConfig callback error = " + JSON.stringify(error)); console.log("setIfaceConfig callback error = " + JSON.stringify(error));
} else { } else {
console.log("setIfaceConfig callback ok "); console.log("setIfaceConfig callback ok ");
} }
}); });
``` ```
...@@ -106,17 +106,17 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void> ...@@ -106,17 +106,17 @@ setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void>
```js ```js
ethernet.setIfaceConfig("eth0", { ethernet.setIfaceConfig("eth0", {
mode: 0, mode: 0,
ipAddr: "192.168.xx.xxx", ipAddr: "192.168.xx.xxx",
route: "192.168.xx.xxx", route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx", gateway: "192.168.xx.xxx",
netMask: "255.255.255.0", netMask: "255.255.255.0",
dnsServers: "1.1.1.1", dnsServers: "1.1.1.1",
domain: "2.2.2.2" domain: "2.2.2.2"
}).then(() => { }).then(() => {
console.log("setIfaceConfig promise ok "); console.log("setIfaceConfig promise ok ");
}).catch(error => { }).catch(error => {
console.log("setIfaceConfig promise error = " + JSON.stringify(error)); console.log("setIfaceConfig promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -154,17 +154,17 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): ...@@ -154,17 +154,17 @@ getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>):
```js ```js
ethernet.getIfaceConfig("eth0", (error, value) => { ethernet.getIfaceConfig("eth0", (error, value) => {
if (error) { if (error) {
console.log("getIfaceConfig callback error = " + JSON.stringify(error)); console.log("getIfaceConfig callback error = " + JSON.stringify(error));
} else { } else {
console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode)); console.log("getIfaceConfig callback mode = " + JSON.stringify(value.mode));
console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr)); console.log("getIfaceConfig callback ipAddr = " + JSON.stringify(value.ipAddr));
console.log("getIfaceConfig callback route = " + JSON.stringify(value.route)); console.log("getIfaceConfig callback route = " + JSON.stringify(value.route));
console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway)); console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway));
console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask)); console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask));
console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers)); console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers));
console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain)); console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain));
} }
}); });
``` ```
...@@ -207,15 +207,15 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration> ...@@ -207,15 +207,15 @@ getIfaceConfig(iface: string): Promise\<InterfaceConfiguration>
```js ```js
ethernet.getIfaceConfig("eth0").then((data) => { ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode)); console.log("getIfaceConfig promise mode = " + JSON.stringify(data.mode));
console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr)); console.log("getIfaceConfig promise ipAddr = " + JSON.stringify(data.ipAddr));
console.log("getIfaceConfig promise route = " + JSON.stringify(data.route)); console.log("getIfaceConfig promise route = " + JSON.stringify(data.route));
console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway)); console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask)); console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers)); console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain)); console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
}).catch(error => { }).catch(error => {
console.log("getIfaceConfig promise error = " + JSON.stringify(error)); console.log("getIfaceConfig promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -253,11 +253,11 @@ isIfaceActive(iface: string, callback: AsyncCallback\<number>): void ...@@ -253,11 +253,11 @@ isIfaceActive(iface: string, callback: AsyncCallback\<number>): void
```js ```js
ethernet.isIfaceActive("eth0", (error, value) => { ethernet.isIfaceActive("eth0", (error, value) => {
if (error) { if (error) {
console.log("whether2Activate callback error = " + JSON.stringify(error)); console.log("whether2Activate callback error = " + JSON.stringify(error));
} else { } else {
console.log("whether2Activate callback = " + JSON.stringify(value)); console.log("whether2Activate callback = " + JSON.stringify(value));
} }
}); });
``` ```
...@@ -300,9 +300,9 @@ isIfaceActive(iface: string): Promise\<number> ...@@ -300,9 +300,9 @@ isIfaceActive(iface: string): Promise\<number>
```js ```js
ethernet.isIfaceActive("eth0").then((data) => { ethernet.isIfaceActive("eth0").then((data) => {
console.log("isIfaceActive promise = " + JSON.stringify(data)); console.log("isIfaceActive promise = " + JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log("isIfaceActive promise error = " + JSON.stringify(error)); console.log("isIfaceActive promise error = " + JSON.stringify(error));
}); });
``` ```
...@@ -336,14 +336,14 @@ getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void ...@@ -336,14 +336,14 @@ getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void
```js ```js
ethernet.getAllActiveIfaces((error, value) => { ethernet.getAllActiveIfaces((error, value) => {
if (error) { if (error) {
console.log("getAllActiveIfaces callback error = " + JSON.stringify(error)); console.log("getAllActiveIfaces callback error = " + JSON.stringify(error));
} else { } else {
console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length)); console.log("getAllActiveIfaces callback value.length = " + JSON.stringify(value.length));
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i])); console.log("getAllActiveIfaces callback = " + JSON.stringify(value[i]));
}
} }
}
}); });
``` ```
...@@ -377,15 +377,83 @@ getAllActiveIfaces(): Promise\<Array\<string>> ...@@ -377,15 +377,83 @@ getAllActiveIfaces(): Promise\<Array\<string>>
```js ```js
ethernet.getAllActiveIfaces().then((data) => { ethernet.getAllActiveIfaces().then((data) => {
console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length)); console.log("getAllActiveIfaces promise data.length = " + JSON.stringify(data.length));
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i])); console.log("getAllActiveIfaces promise = " + JSON.stringify(data[i]));
} }
}).catch(error => { }).catch(error => {
console.log("getAllActiveIfaces promise error = " + JSON.stringify(error)); console.log("getAllActiveIfaces promise error = " + JSON.stringify(error));
}); });
``` ```
## ethernet.on('interfaceStateChange')<sup>10+</sup>
on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void
注册网卡热插拔事件,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Ethernet
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | 是 | 订阅的事件类型,'interfaceStateChange'。 |
| callback | AsyncCallback\<{ iface: string, active: boolean }\> | 是 | 回调函数。<br>iface:网卡名称。<br>active:是否处于激活状态(true:激活;false:未激活) |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**示例:**
```js
ethernet.on('interfaceStateChange', (data) => {
console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
});
```
## ethernet.off('interfaceStateChange')<sup>10+</sup>
off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void
注销网卡热插拔事件,使用callback方式作为异步方法。
**系统接口**:此接口为系统接口。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Ethernet
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | 是 | 订阅的事件类型,'interfaceStateChange'。 |
| callback | AsyncCallback\<{ iface: string, active: boolean }> | 否 | 回调函数。<br>iface:网卡名称。<br>active:是否处于激活状态(true:激活;false:未激活) |
**错误码:**
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**示例:**
```js
ethernet.off('interfaceStateChange');
```
## InterfaceConfiguration ## InterfaceConfiguration
以太网连接配置网络信息。 以太网连接配置网络信息。
......
...@@ -10,6 +10,7 @@ MDNS即多播DNS(Multicast DNS),提供局域网内的本地服务添加、 ...@@ -10,6 +10,7 @@ MDNS即多播DNS(Multicast DNS),提供局域网内的本地服务添加、
```js ```js
import mdns from '@ohos.net.mdns' import mdns from '@ohos.net.mdns'
``` ```
## mdns.addLocalService ## mdns.addLocalService
addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: AsyncCallback\<LocalServiceInfo>): void
...@@ -37,28 +38,28 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: Async ...@@ -37,28 +38,28 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: Async
| 2204008 | Service instance duplicated. | | 2204008 | Service instance duplicated. |
| 2204010 | Send packet failed. | | 2204010 | Send packet failed. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。 > 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。
**示例:** **示例:**
```js ```js
let localServiceInfo = { let localServiceInfo = {
serviceType: "_print._tcp", serviceType: "_print._tcp",
serviceName: "servicename", serviceName: "servicename",
port: 5555, port: 5555,
host: { host: {
address: "10.14.**.***", address: "10.14.**.***",
}, },
serviceAttribute: [{ serviceAttribute: [{
key: "111", key: "111",
value: [1] value: [1]
}] }]
} }
mdns.addLocalService(context, localServiceInfo, function (error, data) { mdns.addLocalService(context, localServiceInfo, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -94,27 +95,27 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<Local ...@@ -94,27 +95,27 @@ addLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<Local
| 2204008 | Service instance duplicated. | | 2204008 | Service instance duplicated. |
| 2204010 | Send packet failed. | | 2204010 | Send packet failed. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。 > 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。
**示例:** **示例:**
```js ```js
let localServiceInfo = { let localServiceInfo = {
serviceType: "_print._tcp", serviceType: "_print._tcp",
serviceName: "servicename", serviceName: "servicename",
port: 5555, port: 5555,
host: { host: {
address: "10.14.**.***", address: "10.14.**.***",
}, },
serviceAttribute: [{ serviceAttribute: [{
key: "111", key: "111",
value: [1] value: [1]
}] }]
} }
mdns.addLocalService(context, localServiceInfo).then(function (data) { mdns.addLocalService(context, localServiceInfo).then(function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -145,28 +146,28 @@ removeLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: As ...@@ -145,28 +146,28 @@ removeLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: As
| 2204008 | Service instance duplicated. | | 2204008 | Service instance duplicated. |
| 2204010 | Send packet failed. | | 2204010 | Send packet failed. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。 > 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。
**示例:** **示例:**
```js ```js
let localServiceInfo = { let localServiceInfo = {
serviceType: "_print._tcp", serviceType: "_print._tcp",
serviceName: "servicename", serviceName: "servicename",
port: 5555, port: 5555,
host: { host: {
address: "10.14.**.***", address: "10.14.**.***",
}, },
serviceAttribute: [{ serviceAttribute: [{
key: "111", key: "111",
value: [1] value: [1]
}] }]
} }
mdns.removeLocalService(context, localServiceInfo, function (error, data) { mdns.removeLocalService(context, localServiceInfo, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -202,27 +203,27 @@ removeLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<Lo ...@@ -202,27 +203,27 @@ removeLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<Lo
| 2204008 | Service instance duplicated. | | 2204008 | Service instance duplicated. |
| 2204010 | Send packet failed. | | 2204010 | Send packet failed. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。 > 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。
**示例:** **示例:**
```js ```js
let localServiceInfo = { let localServiceInfo = {
serviceType: "_print._tcp", serviceType: "_print._tcp",
serviceName: "servicename", serviceName: "servicename",
port: 5555, port: 5555,
host: { host: {
address: "10.14.**.***", address: "10.14.**.***",
}, },
serviceAttribute: [{ serviceAttribute: [{
key: "111", key: "111",
value: [1] value: [1]
}] }]
} }
mdns.removeLocalService(context, localServiceInfo).then(function (data) { mdns.removeLocalService(context, localServiceInfo).then(function (data) {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -282,28 +283,28 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: A ...@@ -282,28 +283,28 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo, callback: A
| 2204006 | Request timeout. | | 2204006 | Request timeout. |
| 2204010 | Send packet failed. | | 2204010 | Send packet failed. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。 > 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。
**示例:** **示例:**
```js ```js
let localServiceInfo = { let localServiceInfo = {
serviceType: "_print._tcp", serviceType: "_print._tcp",
serviceName: "servicename", serviceName: "servicename",
port: 5555, port: 5555,
host: { host: {
address: "10.14.**.***", address: "10.14.**.***",
}, },
serviceAttribute: [{ serviceAttribute: [{
key: "111", key: "111",
value: [1] value: [1]
}] }]
} }
mdns.resolveLocalService(context, localServiceInfo, function (error, data) { mdns.resolveLocalService(context, localServiceInfo, function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -339,27 +340,27 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<L ...@@ -339,27 +340,27 @@ resolveLocalService(context: Context, serviceInfo: LocalServiceInfo): Promise\<L
| 2204006 | Request timeout. | | 2204006 | Request timeout. |
| 2204010 | Send packet failed. | | 2204010 | Send packet failed. |
>**错误码说明:** > **错误码说明:**
> 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。 > 以上错误码的详细介绍参见[MDNS错误码](../errorcodes/errorcode-net-mdns.md)。
**示例:** **示例:**
```js ```js
let localServiceInfo = { let localServiceInfo = {
serviceType: "_print._tcp", serviceType: "_print._tcp",
serviceName: "servicename", serviceName: "servicename",
port: 5555, port: 5555,
host: { host: {
address: "10.14.**.***", address: "10.14.**.***",
}, },
serviceAttribute: [{ serviceAttribute: [{
key: "111", key: "111",
value: [1] value: [1]
}] }]
} }
mdns.resolveLocalService(context, localServiceInfo).then(function (data){ mdns.resolveLocalService(context, localServiceInfo).then(function (data) {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}) })
``` ```
...@@ -420,7 +421,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); ...@@ -420,7 +421,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS(); discoveryService.startSearchingMDNS();
discoveryService.on('discoveryStart', (data) => { discoveryService.on('discoveryStart', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
discoveryService.stopSearchingMDNS(); discoveryService.stopSearchingMDNS();
...@@ -449,7 +450,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); ...@@ -449,7 +450,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS(); discoveryService.startSearchingMDNS();
discoveryService.on('discoveryStop', (data) => { discoveryService.on('discoveryStop', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
discoveryService.stopSearchingMDNS(); discoveryService.stopSearchingMDNS();
...@@ -478,7 +479,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); ...@@ -478,7 +479,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS(); discoveryService.startSearchingMDNS();
discoveryService.on('serviceFound', (data) => { discoveryService.on('serviceFound', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
discoveryService.stopSearchingMDNS(); discoveryService.stopSearchingMDNS();
...@@ -507,7 +508,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType); ...@@ -507,7 +508,7 @@ let discoveryService = mdns.createDiscoveryService(context, serviceType);
discoveryService.startSearchingMDNS(); discoveryService.startSearchingMDNS();
discoveryService.on('serviceLost', (data) => { discoveryService.on('serviceLost', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
discoveryService.stopSearchingMDNS(); discoveryService.stopSearchingMDNS();
......
...@@ -43,10 +43,12 @@ setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\<void>): void ...@@ -43,10 +43,12 @@ setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\<void>): void
```js ```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => { policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); }
)
;
``` ```
## policy.setBackgroundPolicy ## policy.setBackgroundPolicy
...@@ -84,9 +86,9 @@ setBackgroundPolicy(isAllowed: boolean): Promise\<void> ...@@ -84,9 +86,9 @@ setBackgroundPolicy(isAllowed: boolean): Promise\<void>
**示例:** **示例:**
```js ```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -118,9 +120,9 @@ isBackgroundAllowed(callback: AsyncCallback\<boolean>): void ...@@ -118,9 +120,9 @@ isBackgroundAllowed(callback: AsyncCallback\<boolean>): void
```js ```js
policy.isBackgroundAllowed((error, data) => { policy.isBackgroundAllowed((error, data) => {
this.callBack(error, data); this.callBack(error, data);
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}); });
``` ```
...@@ -151,9 +153,9 @@ isBackgroundAllowed(): Promise\<boolean>; ...@@ -151,9 +153,9 @@ isBackgroundAllowed(): Promise\<boolean>;
**示例:** **示例:**
```js ```js
policy.isBackgroundAllowed().then(function(error, data) { policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -190,10 +192,10 @@ setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\<void> ...@@ -190,10 +192,10 @@ setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\<void>
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
} }
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => { policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -234,11 +236,11 @@ setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\<void>; ...@@ -234,11 +236,11 @@ setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\<void>;
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
} }
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) { policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -274,7 +276,7 @@ getPolicyByUid(uid: number, callback: AsyncCallback\<NetUidPolicy>): void ...@@ -274,7 +276,7 @@ getPolicyByUid(uid: number, callback: AsyncCallback\<NetUidPolicy>): void
```js ```js
policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { policy.getPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -313,9 +315,9 @@ getPolicyByUid(uid: number): Promise\<NetUidPolicy>; ...@@ -313,9 +315,9 @@ getPolicyByUid(uid: number): Promise\<NetUidPolicy>;
**示例:** **示例:**
```js ```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -351,7 +353,7 @@ getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\<Array\<number>>): ...@@ -351,7 +353,7 @@ getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\<Array\<number>>):
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => { policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -390,9 +392,9 @@ function getUidsByPolicy(policy: NetUidPolicy): Promise\<Array\<number>>; ...@@ -390,9 +392,9 @@ function getUidsByPolicy(policy: NetUidPolicy): Promise\<Array\<number>>;
**示例:** **示例:**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -425,7 +427,7 @@ getNetQuotaPolicies(callback: AsyncCallback\<Array\<NetQuotaPolicy>>): void ...@@ -425,7 +427,7 @@ getNetQuotaPolicies(callback: AsyncCallback\<Array\<NetQuotaPolicy>>): void
```js ```js
policy.getNetQuotaPolicies((error, data) => { policy.getNetQuotaPolicies((error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -456,9 +458,9 @@ getNetQuotaPolicies(): Promise\<Array\<NetQuotaPolicy>>; ...@@ -456,9 +458,9 @@ getNetQuotaPolicies(): Promise\<Array\<NetQuotaPolicy>>;
**示例:** **示例:**
```js ```js
policy.getNetQuotaPolicies().then(function(error, data) { policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -493,12 +495,22 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallba ...@@ -493,12 +495,22 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallba
**示例:** **示例:**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => { policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -537,13 +549,23 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>): Promise\<void>; ...@@ -537,13 +549,23 @@ setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>): Promise\<void>;
**示例:** **示例:**
```js ```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), let param = {
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param); this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) { policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -579,7 +601,7 @@ restoreAllPolicies(iccid: string, callback: AsyncCallback\<void>): void ...@@ -579,7 +601,7 @@ restoreAllPolicies(iccid: string, callback: AsyncCallback\<void>): void
```js ```js
this.firstParam = iccid; this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam, (error, data) => { policy.restoreAllPolicies(this.firstParam, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -619,9 +641,9 @@ restoreAllPolicies(iccid: string): Promise\<void>; ...@@ -619,9 +641,9 @@ restoreAllPolicies(iccid: string): Promise\<void>;
```js ```js
this.firstParam = iccid; this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){ policy.restoreAllPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -659,10 +681,10 @@ isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\<boolea ...@@ -659,10 +681,10 @@ isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\<boolea
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -704,11 +726,11 @@ isUidNetAllowed(uid: number, isMetered: boolean): Promise\<boolean>; ...@@ -704,11 +726,11 @@ isUidNetAllowed(uid: number, isMetered: boolean): Promise\<boolean>;
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -746,10 +768,10 @@ isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\<boolean>): ...@@ -746,10 +768,10 @@ isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\<boolean>):
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam uid: Number.parseInt(this.firstParam), iface: this.secondParam
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => { policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -790,11 +812,11 @@ isUidNetAllowed(uid: number, iface: string): Promise\<boolean>; ...@@ -790,11 +812,11 @@ isUidNetAllowed(uid: number, iface: string): Promise\<boolean>;
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam uid: Number.parseInt(this.firstParam), iface: this.secondParam
} }
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) { policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -831,10 +853,10 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\ ...@@ -831,10 +853,10 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -875,11 +897,11 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\<void>; ...@@ -875,11 +897,11 @@ setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\<void>;
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -912,7 +934,7 @@ getDeviceIdleAllowList(callback: AsyncCallback\<Array\<number>>): void ...@@ -912,7 +934,7 @@ getDeviceIdleAllowList(callback: AsyncCallback\<Array\<number>>): void
```js ```js
policy.getDeviceIdleAllowList((error, data) => { policy.getDeviceIdleAllowList((error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -943,9 +965,9 @@ getDeviceIdleAllowList(): Promise\<Array\<number>>; ...@@ -943,9 +965,9 @@ getDeviceIdleAllowList(): Promise\<Array\<number>>;
**示例:** **示例:**
```js ```js
policy.getDeviceIdleAllowList().then(function(error, data) { policy.getDeviceIdleAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -981,7 +1003,7 @@ getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\<NetBackgroundPoli ...@@ -981,7 +1003,7 @@ getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\<NetBackgroundPoli
```js ```js
this.firstParam = uid this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => { policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1021,9 +1043,9 @@ getBackgroundPolicyByUid(uid: number): Promise\<NetBackgroundPolicy>; ...@@ -1021,9 +1043,9 @@ getBackgroundPolicyByUid(uid: number): Promise\<NetBackgroundPolicy>;
```js ```js
this.firstParam = uid this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1059,7 +1081,7 @@ resetPolicies(iccid: string, callback: AsyncCallback\<void>): void ...@@ -1059,7 +1081,7 @@ resetPolicies(iccid: string, callback: AsyncCallback\<void>): void
```js ```js
this.firstParam = iccid this.firstParam = iccid
policy.resetPolicies(this.firstParam, (error, data) => { policy.resetPolicies(this.firstParam, (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1098,13 +1120,13 @@ resetPolicies(iccid: string): Promise\<void>; ...@@ -1098,13 +1120,13 @@ resetPolicies(iccid: string): Promise\<void>;
**示例:** **示例:**
```js ```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) { policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
}) })
this.firstParam = iccid this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) { policy.resetPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1142,10 +1164,10 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, ...@@ -1142,10 +1164,10 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType,
```js ```js
let param = { let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
} }
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => { policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1187,11 +1209,11 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): ...@@ -1187,11 +1209,11 @@ updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType):
```js ```js
let param = { let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
} }
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) { policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1228,10 +1250,10 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\< ...@@ -1228,10 +1250,10 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\<
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => { policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1272,11 +1294,11 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\<void>; ...@@ -1272,11 +1294,11 @@ setPowerSaveAllowList(uid: number, isAllowed: boolean): Promise\<void>;
```js ```js
let param = { let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
} }
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) { policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1309,7 +1331,7 @@ getPowerSaveAllowList(callback: AsyncCallback\<Array\<number>>): void ...@@ -1309,7 +1331,7 @@ getPowerSaveAllowList(callback: AsyncCallback\<Array\<number>>): void
```js ```js
policy.getPowerSaveAllowList((error, data) => { policy.getPowerSaveAllowList((error, data) => {
this.callBack(error, data); this.callBack(error, data);
}); });
``` ```
...@@ -1340,9 +1362,9 @@ getPowerSaveAllowList(): Promise\<Array\<number>>; ...@@ -1340,9 +1362,9 @@ getPowerSaveAllowList(): Promise\<Array\<number>>;
**示例:** **示例:**
```js ```js
policy.getPowerSaveAllowList().then(function(error, data) { policy.getPowerSaveAllowList().then(function (error, data) {
console.log(JSON.stringify(error)) console.log(JSON.stringify(error))
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
}) })
``` ```
...@@ -1371,7 +1393,7 @@ on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUid ...@@ -1371,7 +1393,7 @@ on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUid
```js ```js
policy.on('netUidPolicyChange', (data) => { policy.on('netUidPolicyChange', (data) => {
this.log('on netUidPolicyChange:' + JSON.stringify(data)); this.log('on netUidPolicyChange:' + JSON.stringify(data));
}) })
``` ```
...@@ -1396,7 +1418,7 @@ on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule ...@@ -1396,7 +1418,7 @@ on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule
```js ```js
policy.on('netUidRuleChange', (data) => { policy.on('netUidRuleChange', (data) => {
this.log('on netUidRuleChange:' + JSON.stringify(data)); this.log('on netUidRuleChange:' + JSON.stringify(data));
}) })
``` ```
...@@ -1421,7 +1443,7 @@ on(type: "netMeteredIfacesChange", callback: Callback\<Array\<string>>): void ...@@ -1421,7 +1443,7 @@ on(type: "netMeteredIfacesChange", callback: Callback\<Array\<string>>): void
```js ```js
policy.on('netMeteredIfacesChange', (data) => { policy.on('netMeteredIfacesChange', (data) => {
this.log('on netMeteredIfacesChange:' + JSON.stringify(data)); this.log('on netMeteredIfacesChange:' + JSON.stringify(data));
}) })
``` ```
...@@ -1446,7 +1468,7 @@ on(type: "netQuotaPolicyChange", callback: Callback\<Array\<NetQuotaPolicy>>): v ...@@ -1446,7 +1468,7 @@ on(type: "netQuotaPolicyChange", callback: Callback\<Array\<NetQuotaPolicy>>): v
```js ```js
policy.on('netQuotaPolicyChange', (data) => { policy.on('netQuotaPolicyChange', (data) => {
this.log('on netQuotaPolicyChange:' + JSON.stringify(data)); this.log('on netQuotaPolicyChange:' + JSON.stringify(data));
}) })
``` ```
...@@ -1471,7 +1493,7 @@ on(type: "netBackgroundPolicyChange", callback: Callback\<boolean>): void ...@@ -1471,7 +1493,7 @@ on(type: "netBackgroundPolicyChange", callback: Callback\<boolean>): void
```js ```js
policy.on('netBackgroundPolicyChange', (data) => { policy.on('netBackgroundPolicyChange', (data) => {
this.log('on netBackgroundPolicyChange:' + JSON.stringify(data)); this.log('on netBackgroundPolicyChange:' + JSON.stringify(data));
}) })
``` ```
...@@ -1540,10 +1562,8 @@ policy.on('netBackgroundPolicyChange', (data) => { ...@@ -1540,10 +1562,8 @@ policy.on('netBackgroundPolicyChange', (data) => {
**系统能力**:SystemCapability.Communication.NetManager.Core **系统能力**:SystemCapability.Communication.NetManager.Core
| 参数名 | 值 | 说明 | | 参数名 | 值 | 说明 | | ---------------------- | - | ------- | | REMIND_TYPE_WARNING | 1 | 警告提醒 | | REMIND_TYPE_LIMIT | 2 |
| ---------------------- | - | ------- | 限制提醒 |
| REMIND_TYPE_WARNING | 1 | 警告提醒 |
| REMIND_TYPE_LIMIT | 2 | 限制提醒 |
## NetUidPolicy ## NetUidPolicy
......
...@@ -43,8 +43,8 @@ isSharingSupported(callback: AsyncCallback\<boolean>): void ...@@ -43,8 +43,8 @@ isSharingSupported(callback: AsyncCallback\<boolean>): void
```js ```js
sharing.isSharingSupported((error, data) => { sharing.isSharingSupported((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -79,9 +79,9 @@ isSharingSupported(): Promise\<boolean> ...@@ -79,9 +79,9 @@ isSharingSupported(): Promise\<boolean>
```js ```js
sharing.isSharingSupported().then(data => { sharing.isSharingSupported().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -115,8 +115,8 @@ isSharing(callback: AsyncCallback\<boolean>): void ...@@ -115,8 +115,8 @@ isSharing(callback: AsyncCallback\<boolean>): void
```js ```js
sharing.isSharing((error, data) => { sharing.isSharing((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -150,9 +150,9 @@ isSharing(): Promise\<boolean> ...@@ -150,9 +150,9 @@ isSharing(): Promise\<boolean>
```js ```js
sharing.isSharing().then(data => { sharing.isSharing().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -194,9 +194,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -194,9 +194,10 @@ startSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI, (error) => { sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -243,11 +244,12 @@ startSharing(type: SharingIfaceType): Promise\<void> ...@@ -243,11 +244,12 @@ startSharing(type: SharingIfaceType): Promise\<void>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI).then(() => { sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful"); console.log("start wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("start wifi sharing failed"); console.log("start wifi sharing failed");
}); });
``` ```
...@@ -287,9 +289,10 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void ...@@ -287,9 +289,10 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI, (error) => { sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -334,11 +337,12 @@ stopSharing(type: SharingIfaceType): Promise\<void> ...@@ -334,11 +337,12 @@ stopSharing(type: SharingIfaceType): Promise\<void>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI).then(() => { sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful"); console.log("stop wifi sharing successful");
}).catch(error => { }).catch(error => {
console.log("stop wifi sharing failed"); console.log("stop wifi sharing failed");
}); });
``` ```
...@@ -372,8 +376,8 @@ getStatsRxBytes(callback: AsyncCallback\<number>): void ...@@ -372,8 +376,8 @@ getStatsRxBytes(callback: AsyncCallback\<number>): void
```js ```js
sharing.getStatsRxBytes((error, data) => { sharing.getStatsRxBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -407,9 +411,9 @@ getStatsRxBytes(): Promise\<number> ...@@ -407,9 +411,9 @@ getStatsRxBytes(): Promise\<number>
```js ```js
sharing.getStatsRxBytes().then(data => { sharing.getStatsRxBytes().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -443,8 +447,8 @@ getStatsTxBytes(callback: AsyncCallback\<number>): void ...@@ -443,8 +447,8 @@ getStatsTxBytes(callback: AsyncCallback\<number>): void
```js ```js
sharing.getStatsTxBytes((error, data) => { sharing.getStatsTxBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -478,9 +482,9 @@ getStatsTxBytes(): Promise\<number> ...@@ -478,9 +482,9 @@ getStatsTxBytes(): Promise\<number>
```js ```js
sharing.getStatsTxBytes().then(data => { sharing.getStatsTxBytes().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -514,8 +518,8 @@ getStatsTotalBytes(callback: AsyncCallback\<number>): void ...@@ -514,8 +518,8 @@ getStatsTotalBytes(callback: AsyncCallback\<number>): void
```js ```js
sharing.getStatsTotalBytes((error, data) => { sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -549,9 +553,9 @@ getStatsTotalBytes(): Promise\<number> ...@@ -549,9 +553,9 @@ getStatsTotalBytes(): Promise\<number>
```js ```js
sharing.getStatsTotalBytes().then(data => { sharing.getStatsTotalBytes().then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -588,10 +592,11 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin ...@@ -588,10 +592,11 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => { sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -633,11 +638,12 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>> ...@@ -633,11 +638,12 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>>
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => { sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -674,10 +680,11 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta ...@@ -674,10 +680,11 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI, (error, data) => { sharing.getSharingState(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -719,11 +726,12 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState> ...@@ -719,11 +726,12 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI).then(data => { sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -760,10 +768,11 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin ...@@ -760,10 +768,11 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => { sharing.getSharableRegexes(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -805,11 +814,12 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>> ...@@ -805,11 +814,12 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>>
```js ```js
import SharingIfaceType from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => { sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
}); });
``` ```
...@@ -842,8 +852,8 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void ...@@ -842,8 +852,8 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void
**示例:** **示例:**
```js ```js
sharing.on('sharingStateChange', (data) => { sharing.on('sharingStateChange', (data) => {
console.log('on sharingStateChange:' + JSON.stringify(data)); console.log('on sharingStateChange: ' + JSON.stringify(data));
}); });
``` ```
...@@ -877,13 +887,14 @@ off(type: 'sharingStateChange', callback?: Callback\<boolean>): void ...@@ -877,13 +887,14 @@ off(type: 'sharingStateChange', callback?: Callback\<boolean>): void
```js ```js
sharing.off('sharingStateChange', (data) => { sharing.off('sharingStateChange', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
## sharing.on('interfaceSharingStateChange') ## sharing.on('interfaceSharingStateChange')
on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
注册网卡网络共享状态变化事件,使用callback方式作为异步方法。 注册网卡网络共享状态变化事件,使用callback方式作为异步方法。
...@@ -910,14 +921,15 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface ...@@ -910,14 +921,15 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface
**示例:** **示例:**
```js ```js
sharing.on('interfaceSharingStateChange', (data) => { sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange:' + JSON.stringify(data)); console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
}); });
``` ```
## sharing.off('interfaceSharingStateChange') ## sharing.off('interfaceSharingStateChange')
off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state:
SharingIfaceState }>): void
注销网卡网络共享状态变化事件,使用callback方式作为异步方法。 注销网卡网络共享状态变化事件,使用callback方式作为异步方法。
...@@ -945,7 +957,7 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa ...@@ -945,7 +957,7 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa
```js ```js
sharing.off('interfaceSharingStateChange', (data) => { sharing.off('interfaceSharingStateChange', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
...@@ -978,8 +990,8 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void ...@@ -978,8 +990,8 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void
**示例:** **示例:**
```js ```js
sharing.on('sharingUpstreamChange', (data) => { sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange:' + JSON.stringify(data)); console.log('on sharingUpstreamChange:' + JSON.stringify(data));
}); });
``` ```
...@@ -1013,7 +1025,7 @@ off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void ...@@ -1013,7 +1025,7 @@ off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void
```js ```js
sharing.off('sharingUpstreamChange', (data) => { sharing.off('sharingUpstreamChange', (data) => {
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
``` ```
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册