提交 8bf9f28e 编写于 作者: Z zhangxin_T

fix conflict

Signed-off-by: Nzhangxin_T <zhangxin312@huawei.com>
...@@ -12,7 +12,7 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de ...@@ -12,7 +12,7 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de
| API| Return Value| Description| | API| Return Value| Description|
| ---------------------------------------------------------------------------- | --------- | ------------ | | ---------------------------------------------------------------------------- | --------- | ------------ |
| hiTraceMeter.startTrace(name: string, taskId: number, expectedTime?: number) | void | Starts a trace task. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same task ID can be used.| | hiTraceMeter.startTrace(name: string, taskId: number) | void | Starts a trace task. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same task ID can be used.|
| hiTraceMeter.finishTrace(name: string, taskId: number) | void | Stops a trace task. The values of **name** and **taskId** must be the same as those of **hiTraceMeter.startTrace**.| | hiTraceMeter.finishTrace(name: string, taskId: number) | void | Stops a trace task. The values of **name** and **taskId** must be the same as those of **hiTraceMeter.startTrace**.|
| hiTraceMeter.traceByValue(name: string, value: number) | void | Traces the value changes of a variable.| | hiTraceMeter.traceByValue(name: string, value: number) | void | Traces the value changes of a variable.|
...@@ -31,10 +31,6 @@ In this example, distributed call chain tracing begins when the application star ...@@ -31,10 +31,6 @@ In this example, distributed call chain tracing begins when the application star
}, },
onInit() { onInit() {
this.title = this.$t('strings.world'); this.title = this.$t('strings.world');
// The expected duration of the trace task is 5 ms.
hiTraceMeter.startTrace("business", 1);
hiTraceMeter.startTrace("business", 1, 5);
// Start track tasks with the same name concurrently. // Start track tasks with the same name concurrently.
hiTraceMeter.startTrace("business", 1); hiTraceMeter.startTrace("business", 1);
......
...@@ -319,7 +319,7 @@ Checks whether the called number is an emergency number based on the specified p ...@@ -319,7 +319,7 @@ Checks whether the called number is an emergency number based on the specified p
**Example** **Example**
```js ```js
call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, value) => { call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -468,9 +468,7 @@ The phone number must match the specified country code. For example, for a China ...@@ -468,9 +468,7 @@ The phone number must match the specified country code. For example, for a China
**Example** **Example**
```js ```js
call.formatPhoneNumberToE164("138xxxxxxxx",{ call.formatPhoneNumberToE164("138xxxxxxxx", "CN", (err, data) => {
countryCode: "CN"
}, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -504,9 +502,7 @@ All country codes are supported. ...@@ -504,9 +502,7 @@ All country codes are supported.
**Example** **Example**
```js ```js
let promise = call.formatPhoneNumberToE164("138xxxxxxxx", { let promise = call.formatPhoneNumberToE164("138xxxxxxxx", "CN");
countryCode: "CN"
});
promise.then(data => { promise.then(data => {
console.log(`formatPhoneNumberToE164 success, promise: data->${JSON.stringify(data)}`); console.log(`formatPhoneNumberToE164 success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
...@@ -1700,7 +1696,7 @@ This is a system API. ...@@ -1700,7 +1696,7 @@ This is a system API.
**Example** **Example**
```js ```js
isNewCallAllowedcall.on('mmiCodeResult', (err, data) => { call.on('mmiCodeResult', (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -2069,9 +2065,6 @@ This is a system API. ...@@ -2069,9 +2065,6 @@ This is a system API.
**Example** **Example**
```js ```js
let callTransferTyp={
CallTransferType: 1
}
call.getCallTransferInfo(0, callTransferTyp, (err, data) => { call.getCallTransferInfo(0, callTransferTyp, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
...@@ -2104,10 +2097,7 @@ This is a system API. ...@@ -2104,10 +2097,7 @@ This is a system API.
**Example** **Example**
```js ```js
let callTransferTyp={ let promise = call.getCallTransferInfo(0, call.CallTransferType.TRANSFER_TYPE_BUSY);
CallTransferType: 1
}
let promise = call.getCallTransferInfo(0, callTransferTyp);
promise.then(data => { promise.then(data => {
console.log(`getCallTransferInfo success, promise: data->${JSON.stringify(data)}`); console.log(`getCallTransferInfo success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
...@@ -2396,7 +2386,7 @@ This is a system API. ...@@ -2396,7 +2386,7 @@ This is a system API.
let audioDeviceOptions={ let audioDeviceOptions={
bluetoothAddress: "IEEE 802-2014" bluetoothAddress: "IEEE 802-2014"
} }
call.setAudioDevice(1, bluetoothAddress, (err, value) => { call.setAudioDevice(1, audioDeviceOptions, (err, value) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -2460,7 +2450,10 @@ This is a system API. ...@@ -2460,7 +2450,10 @@ This is a system API.
**Example** **Example**
```js ```js
call.joinConference(1, "138XXXXXXXX", (err, data) => { let callNumberList: Array<string> = [
"138XXXXXXXX"
];
call.joinConference(1, callNumberList, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -2491,7 +2484,10 @@ This is a system API. ...@@ -2491,7 +2484,10 @@ This is a system API.
**Example** **Example**
```js ```js
let promise = call.joinConference(1, "138XXXXXXXX"); let callNumberList: Array<string> = [
"138XXXXXXXX"
];
let promise = call.joinConference(1, callNumberList);
promise.then(data => { promise.then(data => {
console.log(`joinConference success, promise: data->${JSON.stringify(data)}`); console.log(`joinConference success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
......
...@@ -304,11 +304,8 @@ hiAppEvent.addWatcher({ ...@@ -304,11 +304,8 @@ hiAppEvent.addWatcher({
console.error("holder is null"); console.error("holder is null");
return; return;
} }
while (true) { let eventPkg = null;
let eventPkg = holder.takeNext(); while ((eventPkg = holder.takeNext()) != null) {
if (eventPkg == null) {
return;
}
console.info("eventPkg.packageId=" + eventPkg.packageId); console.info("eventPkg.packageId=" + eventPkg.packageId);
console.info("eventPkg.row=" + eventPkg.row); console.info("eventPkg.row=" + eventPkg.row);
console.info("eventPkg.size=" + eventPkg.size); console.info("eventPkg.size=" + eventPkg.size);
...@@ -324,15 +321,14 @@ let holder = hiAppEvent.addWatcher({ ...@@ -324,15 +321,14 @@ let holder = hiAppEvent.addWatcher({
name: "watcher2", name: "watcher2",
}); });
if (holder != null) { if (holder != null) {
let eventPkg = holder.takeNext(); let eventPkg = null;
if (eventPkg == null) { while ((eventPkg = holder.takeNext()) != null) {
return; console.info("eventPkg.packageId=" + eventPkg.packageId);
} console.info("eventPkg.row=" + eventPkg.row);
console.info("eventPkg.packageId=" + eventPkg.packageId); console.info("eventPkg.size=" + eventPkg.size);
console.info("eventPkg.row=" + eventPkg.row); for (const eventInfo of eventPkg.data) {
console.info("eventPkg.size=" + eventPkg.size); console.info("eventPkg.data=" + eventInfo);
for (const eventInfo of eventPkg.data) { }
console.info("eventPkg.data=" + eventInfo);
} }
} }
``` ```
...@@ -417,6 +413,9 @@ Sets the data size threshold for fetching an application event package. The defa ...@@ -417,6 +413,9 @@ Sets the data size threshold for fetching an application event package. The defa
**Example** **Example**
```js ```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
holder.setSize(1000); holder.setSize(1000);
``` ```
...@@ -429,6 +428,9 @@ Extracts subscription event data based on the configured data size threshold. If ...@@ -429,6 +428,9 @@ Extracts subscription event data based on the configured data size threshold. If
**Example** **Example**
```js ```js
let holder = hiAppEvent.addWatcher({
name: "watcher",
});
let eventPkg = holder.takeNext(); let eventPkg = holder.takeNext();
``` ```
......
...@@ -30,9 +30,10 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -30,9 +30,10 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
**Example** **Example**
```js
let nativeHeapSize = hidebug.getNativeHeapSize(); ```js
``` let nativeHeapSize = hidebug.getNativeHeapSize();
```
## hidebug.getNativeHeapAllocatedSize ## hidebug.getNativeHeapAllocatedSize
...@@ -45,17 +46,18 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -45,17 +46,18 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | --------------------------------- | | ------ | --------------------------------- |
| bigint | Size of the allocated native heap memory, in kB.| | bigint | Size of the allocated native heap memory, in kB.|
**Example** **Example**
```js
let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); ```js
``` let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize();
```
## hidebug.getNativeHeapFreeSize ## hidebug.getNativeHeapFreeSize
...@@ -68,17 +70,18 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. ...@@ -68,17 +70,18 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------------- | | ------ | ------------------------------- |
| bigint | Size of the free native heap memory, in kB.| | bigint | Size of the free native heap memory, in kB.|
**Example** **Example**
```js
let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); ```js
``` let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize();
```
## hidebug.getPss ## hidebug.getPss
...@@ -89,17 +92,18 @@ Obtains the PSS of this process. ...@@ -89,17 +92,18 @@ Obtains the PSS of this process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------- | | ------ | ------------------------- |
| bigint | PSS of the process, in kB.| | bigint | PSS of the process, in kB.|
**Example** **Example**
```js
let pss = hidebug.getPss(); ```js
``` let pss = hidebug.getPss();
```
## hidebug.getSharedDirty ## hidebug.getSharedDirty
...@@ -110,17 +114,18 @@ Obtains the size of the shared dirty memory of this process. ...@@ -110,17 +114,18 @@ Obtains the size of the shared dirty memory of this process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| bigint | Size of the shared dirty memory of the process, in kB.| | bigint | Size of the shared dirty memory of the process, in kB.|
**Example** **Example**
```js
let sharedDirty = hidebug.getSharedDirty(); ```js
``` let sharedDirty = hidebug.getSharedDirty();
```
## hidebug.getPrivateDirty<sup>9+<sup> ## hidebug.getPrivateDirty<sup>9+<sup>
...@@ -130,8 +135,8 @@ Obtains the size of the private dirty memory of this process. ...@@ -130,8 +135,8 @@ Obtains the size of the private dirty memory of this process.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| bigint | Size of the private dirty memory of the process, in kB.| | bigint | Size of the private dirty memory of the process, in kB.|
...@@ -152,17 +157,18 @@ For example, if the CPU usage is **50%**, **0.5** is returned. ...@@ -152,17 +157,18 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| number | CPU usage of the process.| | number | CPU usage of the process.|
**Example** **Example**
```js
let cpuUsage = hidebug.getCpuUsage(); ```js
``` let cpuUsage = hidebug.getCpuUsage();
```
## hidebug.startProfiling ## hidebug.startProfiling
...@@ -189,7 +195,6 @@ hidebug.stopProfiling(); ...@@ -189,7 +195,6 @@ hidebug.stopProfiling();
``` ```
## hidebug.stopProfiling ## hidebug.stopProfiling
stopProfiling() : void stopProfiling() : void
...@@ -245,6 +250,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -245,6 +250,7 @@ This is a system API and cannot be called by third-party applications.
| serviceid | number | Yes | ID of the system service. | | serviceid | number | Yes | ID of the system service. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------------- | | ------ | -------------------------- |
| string | Absolute path of the file that contains the service information to dump. | | string | Absolute path of the file that contains the service information to dump. |
......
...@@ -60,20 +60,24 @@ Writes event information to the event file. This API uses an asynchronous callba ...@@ -60,20 +60,24 @@ Writes event information to the event file. This API uses an asynchronous callba
```js ```js
import hiSysEvent from '@ohos.hiSysEvent'; import hiSysEvent from '@ohos.hiSysEvent';
hiSysEvent.write({ try {
domain: "RELIABILITY", hiSysEvent.write({
name: "STACK", domain: "RELIABILITY",
eventType: hiSysEvent.EventType.FAULT, name: "STACK",
params: { eventType: hiSysEvent.EventType.FAULT,
PID: 487, params: {
UID: 103, PID: 487,
PACKAGE_NAME: "com.ohos.hisysevent.test", UID: 103,
PROCESS_NAME: "syseventservice", PACKAGE_NAME: "com.ohos.hisysevent.test",
MSG: "no msg." PROCESS_NAME: "syseventservice",
} MSG: "no msg."
}, (err, val) => { }
// do something here. }, (err, val) => {
}) // do something here.
})
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
}
``` ```
...@@ -102,26 +106,30 @@ Writes event information to the event file. This API uses a promise to return th ...@@ -102,26 +106,30 @@ Writes event information to the event file. This API uses a promise to return th
```js ```js
import hiSysEvent from '@ohos.hiSysEvent'; import hiSysEvent from '@ohos.hiSysEvent';
hiSysEvent.write({ try {
domain: "RELIABILITY", hiSysEvent.write({
name: "STACK", domain: "RELIABILITY",
eventType: hiSysEvent.EventType.FAULT, name: "STACK",
params: { eventType: hiSysEvent.EventType.FAULT,
PID: 487, params: {
UID: 103, PID: 487,
PACKAGE_NAME: "com.ohos.hisysevent.test", UID: 103,
PROCESS_NAME: "syseventservice", PACKAGE_NAME: "com.ohos.hisysevent.test",
MSG: "no msg." PROCESS_NAME: "syseventservice",
} MSG: "no msg."
}).then( }
(val) => { }).then(
// do something here. (val) => {
} // do something here.
).catch( }
(err) => { ).catch(
// do something here. (err) => {
} // do something here.
) }
)
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
}
``` ```
## RuleType ## RuleType
...@@ -177,32 +185,30 @@ Adds a watcher for event subscription. ...@@ -177,32 +185,30 @@ Adds a watcher for event subscription.
| ------ | ----------------------------- | ---- | ------------------------ | | ------ | ----------------------------- | ---- | ------------------------ |
| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
**Return value**
| Type | Description|
| ------- | -------------------------------------------------- |
| number | Event subscription result.<br>- **0**: Event subscription is successful.<br>- A value smaller than **0**: Event subscription has failed.|
**Example** **Example**
```js ```js
import hiSysEvent from '@ohos.hiSysEvent'; import hiSysEvent from '@ohos.hiSysEvent';
let watcher = { let watcher = {
rules: [{ rules: [{
domain: "RELIABILITY", domain: "RELIABILITY",
name: "STACK", name: "STACK",
tag: "STABILITY", tag: "STABILITY",
ruleType: hiSysEvent.RuleType.WHOLE_WORD, ruleType: hiSysEvent.RuleType.WHOLE_WORD,
}], }],
onEvent: (info) => { onEvent: (info) => {
// do something here. // do something here.
}, },
onServiceDied: () => { onServiceDied: () => {
// do something here. // do something here.
} }
}
try {
hiSysEvent.addWatcher(watcher)
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
} }
let ret = hiSysEvent.addWatcher(watcher)
``` ```
## hiSysEvent.removeWatcher ## hiSysEvent.removeWatcher
...@@ -221,33 +227,31 @@ Removes a watcher used for event subscription. ...@@ -221,33 +227,31 @@ Removes a watcher used for event subscription.
| ------ | ------------- | ---- | ------------------------ | | ------ | ------------- | ---- | ------------------------ |
| watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.|
**Return value**
| Type | Description|
| ------- | ----------------------------------------------------------- |
| number | Result of removing the watcher.<br>- **0**: Removing the watcher is successful.<br>- A value smaller than **0**: Removing the watcher has failed.|
**Example** **Example**
```js ```js
import hiSysEvent from '@ohos.hiSysEvent'; import hiSysEvent from '@ohos.hiSysEvent';
let watcher = { let watcher = {
rules: [{ rules: [{
domain: "RELIABILITY", domain: "RELIABILITY",
name: "STACK", name: "STACK",
tag: "STABILITY", tag: "STABILITY",
ruleType: hiSysEvent.RuleType.WHOLE_WORD, ruleType: hiSysEvent.RuleType.WHOLE_WORD,
}], }],
onEvent: (info) => { onEvent: (info) => {
// do something here. // do something here.
}, },
onServiceDied: () => { onServiceDied: () => {
// do something here. // do something here.
} }
}
try {
hiSysEvent.addWatcher(watcher)
hiSysEvent.removeWatcher(watcher)
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
} }
let ret = hiSysEvent.addWatcher(watcher)
hiSysEvent.removeWatcher(watcher)
``` ```
## QueryArg ## QueryArg
...@@ -281,7 +285,7 @@ Defines an event query instance. ...@@ -281,7 +285,7 @@ Defines an event query instance.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[], seqs: number[]) => void| | onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void|
| onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| | onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void|
## hiSysEvent.query ## hiSysEvent.query
...@@ -302,44 +306,42 @@ Queries system events. ...@@ -302,44 +306,42 @@ Queries system events.
| rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.|
| querier | [Querier](#querier) | Yes | Event query instance.| | querier | [Querier](#querier) | Yes | Event query instance.|
**Return value**
| Type | Description |
| ------- | ----------------------------------------------------------- |
| number | Event query result.<br>- **0**: Event query is successful.<br>- A value smaller than **0**: Event query has failed.|
**Example** **Example**
```js ```js
import hiSysEvent from '@ohos.hiSysEvent'; import hiSysEvent from '@ohos.hiSysEvent';
hiSysEvent.write({ try {
domain: "RELIABILITY", hiSysEvent.write({
name: "STACK", domain: "RELIABILITY",
eventType: hiSysEvent.EventType.FAULT, name: "STACK",
params: { eventType: hiSysEvent.EventType.FAULT,
PID: 487, params: {
UID: 103, PID: 487,
PACKAGE_NAME: "com.ohos.hisysevent.test", UID: 103,
PROCESS_NAME: "syseventservice", PACKAGE_NAME: "com.ohos.hisysevent.test",
MSG: "no msg." PROCESS_NAME: "syseventservice",
} MSG: "no msg."
}, (err, val) => { }
// do something here. }, (err, val) => {
}) // do something here.
hiSysEvent.query({ })
beginTime: -1, hiSysEvent.query({
endTime: -1, beginTime: -1,
maxEvents: 5, endTime: -1,
}, [{ maxEvents: 5,
domain: "RELIABILITY", }, [{
names: ["STACK"], domain: "RELIABILITY",
}], { names: ["STACK"],
onQuery: function (infos, seqs) { }], {
// do something here. onQuery: function (infos) {
}, // do something here.
onComplete: function(reason, total) { },
// do something here. onComplete: function(reason, total) {
} // do something here.
}) }
})
} catch (error) {
console.error(`error code: ${error.code}, error msg: ${error.message}`);
}
``` ```
...@@ -71,7 +71,7 @@ Defines a **HiTraceId** object. ...@@ -71,7 +71,7 @@ Defines a **HiTraceId** object.
## hiTraceChain.begin ## hiTraceChain.begin
begin(name: string, flags: number = HiTraceFlag.DEFAULT): HiTraceId begin(name: string, flags?: number): HiTraceId
Starts call chain tracing. This API works in synchronous manner. Starts call chain tracing. This API works in synchronous manner.
...@@ -82,7 +82,7 @@ Starts call chain tracing. This API works in synchronous manner. ...@@ -82,7 +82,7 @@ Starts call chain tracing. This API works in synchronous manner.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Traced service name. | | name | string | Yes| Traced service name. |
| flags | number | Yes| Trace flag combination. For details, see [HiTraceFlag](#hitraceflag). | | flags | number | No| Trace flag combination. For details, see [HiTraceFlag](#hitraceflag). |
**Return Value** **Return Value**
...@@ -113,7 +113,7 @@ Stops call chain tracing. This API works in synchronous manner. ...@@ -113,7 +113,7 @@ Stops call chain tracing. This API works in synchronous manner.
**Example** **Example**
```js ```js
let asyncTraceId = hiTraceChain.begin("business"); let asyncTraceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT);
// End the call chain tracing after the service logic is executed for several times. // End the call chain tracing after the service logic is executed for several times.
hiTraceChain.end(asyncTraceId); hiTraceChain.end(asyncTraceId);
``` ```
...@@ -135,7 +135,7 @@ Obtains the trace ID. This API works in synchronous manner. ...@@ -135,7 +135,7 @@ Obtains the trace ID. This API works in synchronous manner.
**Example** **Example**
```js ```js
let traceId = hiTraceChain.begin("business"); let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT);
// Obtain the current trace ID after the service logic is executed for several times. // Obtain the current trace ID after the service logic is executed for several times.
let curTraceId = hiTraceChain.getId(); let curTraceId = hiTraceChain.getId();
``` ```
...@@ -158,7 +158,7 @@ Sets a trace ID. This API works in synchronous manner. ...@@ -158,7 +158,7 @@ Sets a trace ID. This API works in synchronous manner.
```js ```js
let asyncTraceId; let asyncTraceId;
let traceId = hiTraceChain.begin("business"); let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT);
// Set the current trace ID after the service logic is executed for several times. // Set the current trace ID after the service logic is executed for several times.
hiTraceChain.setId(asyncTraceId); hiTraceChain.setId(asyncTraceId);
``` ```
...@@ -174,7 +174,7 @@ Clears the trace ID. This API works in synchronous manner. ...@@ -174,7 +174,7 @@ Clears the trace ID. This API works in synchronous manner.
**Example** **Example**
```js ```js
let traceId = hiTraceChain.begin("business"); let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT);
// Clear the current trace ID after the service logic is executed for several times. // Clear the current trace ID after the service logic is executed for several times.
hiTraceChain.clearId(); hiTraceChain.clearId();
``` ```
...@@ -196,7 +196,7 @@ Creates a trace span. This API works in synchronous manner. ...@@ -196,7 +196,7 @@ Creates a trace span. This API works in synchronous manner.
**Example** **Example**
```js ```js
let traceId = hiTraceChain.begin("business"); let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT);
// Create a trace span after the service logic is executed for several times. // Create a trace span after the service logic is executed for several times.
let spanTraceId = hiTraceChain.createSpan(); let spanTraceId = hiTraceChain.createSpan();
``` ```
...@@ -249,7 +249,7 @@ Checks whether a **HiTraceId** instance is valid. This API works in synchronous ...@@ -249,7 +249,7 @@ Checks whether a **HiTraceId** instance is valid. This API works in synchronous
**Example** **Example**
```js ```js
let traceId = hiTraceChain.begin("business"); let traceId = hiTraceChain.begin("business", hiTraceChain.HiTraceFlag.DEFAULT);
let traceIdIsvalid = hiTraceChain.isValid(traceId); let traceIdIsvalid = hiTraceChain.isValid(traceId);
``` ```
...@@ -291,6 +291,7 @@ Enables the specified trace flag in the **HiTraceId** instance. This API works i ...@@ -291,6 +291,7 @@ Enables the specified trace flag in the **HiTraceId** instance. This API works i
**System capability**: SystemCapability.HiviewDFX.HiTrace **System capability**: SystemCapability.HiviewDFX.HiTrace
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| id | [HiTraceId](#hitraceid) | Yes | **HiTraceId** instance. | | id | [HiTraceId](#hitraceid) | Yes | **HiTraceId** instance. |
......
...@@ -404,7 +404,7 @@ Provides the device capability. ...@@ -404,7 +404,7 @@ Provides the device capability.
| currencyDisplay | string | Yes | Yes | Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| | currencyDisplay | string | Yes | Yes | Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.|
| unit | string | Yes | Yes | Unit name, for example, **meter**, **inch**, or **hectare**. | | unit | string | Yes | Yes | Unit name, for example, **meter**, **inch**, or **hectare**. |
| unitDisplay | string | Yes | Yes | Unit display format. The value can be **long**, **short**, or **narrow**.| | unitDisplay | string | Yes | Yes | Unit display format. The value can be **long**, **short**, or **narrow**.|
| unitUsage<sup>8+</sup> | string | Yes | Yes | Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.| | unitUsage | string | Yes | Yes | Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.|
| signDisplay | string | Yes | Yes | Number sign display format. The value can be **auto**, **never**, **always**, or **expectZero**.| | signDisplay | string | Yes | Yes | Number sign display format. The value can be **auto**, **never**, **always**, or **expectZero**.|
| compactDisplay | string | Yes | Yes | Compact display format. The value can be **long** or **short**. | | compactDisplay | string | Yes | Yes | Compact display format. The value can be **long** or **short**. |
| notation | string | Yes | Yes | Number formatting specification. The value can be **standard**, **scientific**, **engineering**, or **compact**.| | notation | string | Yes | Yes | Number formatting specification. The value can be **standard**, **scientific**, **engineering**, or **compact**.|
......
...@@ -96,7 +96,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode' ...@@ -96,7 +96,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'
| KEYCODE_EQUALS | number | Yes| No| Key =| | KEYCODE_EQUALS | number | Yes| No| Key =|
| KEYCODE_LEFT_BRACKET | number | Yes| No| Key [| | KEYCODE_LEFT_BRACKET | number | Yes| No| Key [|
| KEYCODE_RIGHT_BRACKET | number | Yes| No| Key ]| | KEYCODE_RIGHT_BRACKET | number | Yes| No| Key ]|
| KEYCODE_BACKSLASH | number | Yes| No| Key \| | KEYCODE_BACKSLASH | number | Yes| No| Key \\|
| KEYCODE_SEMICOLON | number | Yes| No| Key ;| | KEYCODE_SEMICOLON | number | Yes| No| Key ;|
| KEYCODE_APOSTROPHE | number | Yes| No| Key ' | | KEYCODE_APOSTROPHE | number | Yes| No| Key ' |
| KEYCODE_SLASH | number | Yes| No| Key /| | KEYCODE_SLASH | number | Yes| No| Key /|
......
...@@ -47,7 +47,7 @@ Obtains the default active data network. This API uses a promise to return the r ...@@ -47,7 +47,7 @@ Obtains the default active data network. This API uses a promise to return the r
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Return Value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
...@@ -92,7 +92,7 @@ Checks whether the default data network is activated. This API uses a promise to ...@@ -92,7 +92,7 @@ Checks whether the default data network is activated. This API uses a promise to
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ----------------- | ----------------------------------------------- | | ----------------- | ----------------------------------------------- |
...@@ -117,6 +117,7 @@ Obtains the list of all active data networks. This API uses an asynchronous call ...@@ -117,6 +117,7 @@ Obtains the list of all active data networks. This API uses an asynchronous call
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Yes| Callback used to return the result.|
...@@ -141,7 +142,8 @@ Obtains the list of all active data networks. This API uses a promise to return ...@@ -141,7 +142,8 @@ Obtains the list of all active data networks. This API uses a promise to return
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Return Value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | Promise used to return the result.|
...@@ -198,7 +200,7 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi ...@@ -198,7 +200,7 @@ Obtains connection properties of the network corresponding to **netHandle**. Thi
| --------- | ----------------------- | ---- | ---------------- | | --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------------------------- | --------------------------------- | | ------------------------------------------------------- | --------------------------------- |
...@@ -258,7 +260,7 @@ Obtains capability information of the network corresponding to **netHandle**. Th ...@@ -258,7 +260,7 @@ Obtains capability information of the network corresponding to **netHandle**. Th
| --------- | ----------------------- | ---- | ---------------- | | --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.| | netHandle | [NetHandle](#nethandle) | Yes | Handle of the data network.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------------------- | --------------------------------- | | --------------------------------------------- | --------------------------------- |
...@@ -285,6 +287,7 @@ Reports connection of the data network. This API uses an asynchronous callback t ...@@ -285,6 +287,7 @@ Reports connection of the data network. This API uses an asynchronous callback t
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
...@@ -312,11 +315,13 @@ Reports connection of the data network. This API uses a promise to return the re ...@@ -312,11 +315,13 @@ Reports connection of the data network. This API uses a promise to return the re
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return Value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
...@@ -343,6 +348,7 @@ Reports disconnection of the data network. This API uses an asynchronous callbac ...@@ -343,6 +348,7 @@ Reports disconnection of the data network. This API uses an asynchronous callbac
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
...@@ -370,11 +376,13 @@ Reports disconnection of the data network. This API uses a promise to return the ...@@ -370,11 +376,13 @@ Reports disconnection of the data network. This API uses a promise to return the
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).| | netHandle | [NetHandle](#nethandle) | Yes| Handle of the data network. For details, see [NetHandle](#nethandle).|
**Return Value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
...@@ -432,7 +440,7 @@ Resolves the host name by using the default network to obtain all IP addresses. ...@@ -432,7 +440,7 @@ Resolves the host name by using the default network to obtain all IP addresses.
| ------ | ------ | ---- | ------------------ | | ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to be resolved.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
...@@ -561,7 +569,7 @@ Obtains the handle of the network specified by **netSpecifier**. ...@@ -561,7 +569,7 @@ Obtains the handle of the network specified by **netSpecifier**.
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. | | netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. |
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.| | timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------- | -------------------- | | ------------------------------- | -------------------- |
...@@ -829,7 +837,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre ...@@ -829,7 +837,7 @@ Resolves the host name by using the corresponding network to obtain all IP addre
| ------ | ------ | ---- | ------------------ | | ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to be resolved.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------------- | ----------------------------- | | ------------------------------------------- | ----------------------------- |
...@@ -891,7 +899,7 @@ Resolves the host name by using the corresponding network to obtain the first IP ...@@ -891,7 +899,7 @@ Resolves the host name by using the corresponding network to obtain the first IP
| ------ | ------ | ---- | ------------------ | | ------ | ------ | ---- | ------------------ |
| host | string | Yes | Host name to be resolved.| | host | string | Yes | Host name to be resolved.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------- | ------------------------------- | | ----------------------------------- | ------------------------------- |
......
...@@ -1100,12 +1100,12 @@ Sets the network selection mode. This API uses an asynchronous callback to retur ...@@ -1100,12 +1100,12 @@ Sets the network selection mode. This API uses an asynchronous callback to retur
let networkInformation={ let networkInformation={
operatorName: "China Mobile", operatorName: "China Mobile",
operatorNumeric: "898600", operatorNumeric: "898600",
state: 1, state: radio.NetworkInformationState.NETWORK_AVAILABLE,
radioTech: "CS" radioTech: "CS"
} }
let networkSelectionModeOptions={ let networkSelectionModeOptions={
slotid: 0, slotId: 0,
selectMode: 1, selectMode: radio.NetworkSelectionMode.NETWORK_SELECTION_AUTOMATIC,
networkInformation: networkInformation, networkInformation: networkInformation,
resumeSelection: true resumeSelection: true
} }
...@@ -1144,12 +1144,12 @@ Sets the network selection mode. This API uses a promise to return the result. ...@@ -1144,12 +1144,12 @@ Sets the network selection mode. This API uses a promise to return the result.
let networkInformation={ let networkInformation={
operatorName: "China Mobile", operatorName: "China Mobile",
operatorNumeric: "898600", operatorNumeric: "898600",
state: 1, state: radio.NetworkInformationState.NETWORK_AVAILABLE,
radioTech: "CS" radioTech: "CS"
} }
let networkSelectionModeOptions={ let networkSelectionModeOptions={
slotid: 0, slotId: 0,
selectMode: 1, selectMode: radio.NetworkSelectionMode.NETWORK_SELECTION_AUTOMATIC,
networkInformation: networkInformation, networkInformation: networkInformation,
resumeSelection: true resumeSelection: true
} }
...@@ -1190,7 +1190,7 @@ radio.getNetworkSearchInformation(0, (err, data) => { ...@@ -1190,7 +1190,7 @@ radio.getNetworkSearchInformation(0, (err, data) => {
## radio.getNetworkSearchInformation ## radio.getNetworkSearchInformation
getNetworkSearchInformation\(slotId: number\): Promise<void\> getNetworkSearchInformation\(slotId: number\): Promise<NetworkSearchResult\>
Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result. Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result.
...@@ -1586,7 +1586,7 @@ radio.getPreferredNetwork(0, (err, data) => { ...@@ -1586,7 +1586,7 @@ radio.getPreferredNetwork(0, (err, data) => {
## radio.getPreferredNetwork<sup>8+</sup> ## radio.getPreferredNetwork<sup>8+</sup>
getPreferredNetwork(slotId: number): Promise<void\> getPreferredNetwork(slotId: number): Promise<PreferredNetworkMode\>
Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result.
...@@ -1642,7 +1642,7 @@ Obtains the IMS registration status of the specified IMS service type for the SI ...@@ -1642,7 +1642,7 @@ Obtains the IMS registration status of the specified IMS service type for the SI
**Example** **Example**
```js ```js
radio.getImsRegInfo(0, 1, (err, data) => { radio.getImsRegInfo(0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1675,7 +1675,7 @@ Obtains the IMS registration status of the specified IMS service type for the SI ...@@ -1675,7 +1675,7 @@ Obtains the IMS registration status of the specified IMS service type for the SI
**Example** **Example**
```js ```js
let promise = radio.getImsRegInfo(0, 1); let promise = radio.getImsRegInfo(0, radio.ImsServiceType.TYPE_VIDEO);
promise.then(data => { promise.then(data => {
console.log(`getImsRegInfo success, promise: data->${JSON.stringify(data)}`); console.log(`getImsRegInfo success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
...@@ -1707,7 +1707,7 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci ...@@ -1707,7 +1707,7 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci
**Example** **Example**
```js ```js
radio.on('imsRegStateChange', 0, 1, (err, data) => { radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1736,7 +1736,7 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec ...@@ -1736,7 +1736,7 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec
**Example** **Example**
```js ```js
radio.off('imsRegStateChange', 0, 1, (err, data) => { radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
......
...@@ -589,7 +589,7 @@ Obtains the account information list of the active SIM card. This API uses an as ...@@ -589,7 +589,7 @@ Obtains the account information list of the active SIM card. This API uses an as
**Example** **Example**
```js ```js
sim.getActiveSimAccountInfoList(0, (err, data) => { sim.getActiveSimAccountInfoList((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy ...@@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy
**Example** **Example**
```js ```js
const name='China Mobile'; let name = 'China Mobile';
sim.setShowName(0, name, (err, data) => { sim.setShowName(0, name, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
...@@ -744,7 +744,7 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom ...@@ -744,7 +744,7 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom
**Example** **Example**
```js ```js
const name='China Mobile'; let name = 'China Mobile';
let promise = sim.setShowName(0, name); let promise = sim.setShowName(0, name);
promise.then(data => { promise.then(data => {
console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); console.log(`setShowName success, promise: data->${JSON.stringify(data)}`);
...@@ -1096,9 +1096,9 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy ...@@ -1096,9 +1096,9 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy
```js ```js
let lockInfo = { let lockInfo = {
lockType = 1, lockType: sim.LockType.PIN_LOCK,
password = "1234", password = "1234",
state = 0 state: sim.LockState.LOCK_OFF
}; };
sim.setLockState(0, lockInfo, (err, data) => { sim.setLockState(0, lockInfo, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
...@@ -1135,9 +1135,9 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom ...@@ -1135,9 +1135,9 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom
```js ```js
let lockInfo = { let lockInfo = {
lockType = 1, lockType: sim.LockType.PIN_LOCK,
password = "1234", password = "1234",
state = 0 state: sim.LockState.LOCK_OFF
}; };
let promise = sim.setLockState(0, lockInfo); let promise = sim.setLockState(0, lockInfo);
promise.then(data => { promise.then(data => {
...@@ -2236,12 +2236,12 @@ Adds contact numbers for the SIM card in the specified slot. This API uses an as ...@@ -2236,12 +2236,12 @@ Adds contact numbers for the SIM card in the specified slot. This API uses an as
```js ```js
let diallingNumbersInof = { let diallingNumbersInof = {
alphaTag = "alpha", alphaTag: "alpha",
number = "138xxxxxxxx", number: "138xxxxxxxx",
recordNumber = 123, recordNumber: 123,
pin2 = "1234" pin2: "1234"
}; };
sim.addIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -2277,12 +2277,12 @@ Adds contact numbers for the SIM card in the specified slot. This API uses a pro ...@@ -2277,12 +2277,12 @@ Adds contact numbers for the SIM card in the specified slot. This API uses a pro
```js ```js
let diallingNumbersInof = { let diallingNumbersInof = {
alphaTag = "alpha", alphaTag: "alpha",
number = "138xxxxxxxx", number: "138xxxxxxxx",
recordNumber = 123, recordNumber: 123,
pin2 = "1234" pin2: "1234"
}; };
let promise = sim.addIccDiallingNumbers(0, 1, diallingNumbersInof); let promise = sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof);
promise.then(data => { promise.then(data => {
console.log(`addIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); console.log(`addIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
...@@ -2315,12 +2315,12 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a ...@@ -2315,12 +2315,12 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a
```js ```js
let diallingNumbersInof = { let diallingNumbersInof = {
alphaTag = "alpha", alphaTag: "alpha",
number = "138xxxxxxxx", number: "138xxxxxxxx",
recordNumber = 123, recordNumber: 123,
pin2 = "1234" pin2: "1234"
}; };
sim.delIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -2356,12 +2356,12 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a ...@@ -2356,12 +2356,12 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a
```js ```js
let diallingNumbersInof = { let diallingNumbersInof = {
alphaTag = "alpha", alphaTag: "alpha",
number = "138xxxxxxxx", number: "138xxxxxxxx",
recordNumber = 123, recordNumber: 123,
pin2 = "1234" pin2: "1234"
}; };
let promise = sim.delIccDiallingNumbers(0, 1, diallingNumbersInof); let promise = sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof);
promise.then(data => { promise.then(data => {
console.log(`delIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); console.log(`delIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
...@@ -2394,12 +2394,12 @@ Updates contact numbers for the SIM card in the specified slot. This API uses an ...@@ -2394,12 +2394,12 @@ Updates contact numbers for the SIM card in the specified slot. This API uses an
```js ```js
let diallingNumbersInof = { let diallingNumbersInof = {
alphaTag = "alpha", alphaTag: "alpha",
number = "138xxxxxxxx", number: "138xxxxxxxx",
recordNumber = 123, recordNumber: 123,
pin2 = "1234" pin2: "1234"
}; };
sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -2435,12 +2435,12 @@ Updates contact numbers for the SIM card in the specified slot. This API uses a ...@@ -2435,12 +2435,12 @@ Updates contact numbers for the SIM card in the specified slot. This API uses a
```js ```js
let diallingNumbersInof = { let diallingNumbersInof = {
alphaTag = "alpha", alphaTag: "alpha",
number = "138xxxxxxxx", number: "138xxxxxxxx",
recordNumber = 123, recordNumber: 123,
pin2 = "1234" pin2: "1234"
}; };
let promise = sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof); let promise = sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof);
promise.then(data => { promise.then(data => {
console.log(`updateIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); console.log(`updateIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
...@@ -2602,7 +2602,7 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba ...@@ -2602,7 +2602,7 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba
```js ```js
let persoLockInfo = { let persoLockInfo = {
lockType = 0, lockType = sim.PersoLockType.PN_PIN_LOCK,
password = "1234" password = "1234"
}; };
sim.unlockSimLock(0, persoLockInfo, (err, data) => { sim.unlockSimLock(0, persoLockInfo, (err, data) => {
...@@ -2640,7 +2640,7 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th ...@@ -2640,7 +2640,7 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th
```js ```js
let persoLockInfo = { let persoLockInfo = {
lockType = 0, lockType = sim.PersoLockType.PN_PIN_LOCK,
password = "1234" password = "1234"
}; };
let promise = sim.unlockSimLock(0, persoLockInfo); let promise = sim.unlockSimLock(0, persoLockInfo);
......
...@@ -397,7 +397,7 @@ Splits an SMS message into multiple segments. This API uses an asynchronous call ...@@ -397,7 +397,7 @@ Splits an SMS message into multiple segments. This API uses an asynchronous call
**Example** **Example**
```js ```js
string content= "long message"; let content = "long message";
sms.splitMessage(content, (err, data) => { sms.splitMessage(content, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
...@@ -431,7 +431,7 @@ Splits an SMS message into multiple segments. This API uses a promise to return ...@@ -431,7 +431,7 @@ Splits an SMS message into multiple segments. This API uses a promise to return
**Example** **Example**
```js ```js
string content = "long message"; let content = "long message";
let promise = sms.splitMessage(content); let promise = sms.splitMessage(content);
promise.then(data => { promise.then(data => {
console.log(`splitMessage success, promise: data->${JSON.stringify(data)}`); console.log(`splitMessage success, promise: data->${JSON.stringify(data)}`);
...@@ -463,10 +463,10 @@ Adds a SIM message. This API uses an asynchronous callback to return the result. ...@@ -463,10 +463,10 @@ Adds a SIM message. This API uses an asynchronous callback to return the result.
```js ```js
let simMessageOptions = { let simMessageOptions = {
slotId = 0, slotId: 0,
smsc = "test", smsc: "test",
pdu = "xxxxxx", pdu: "xxxxxx",
status = 0 status: sms.SimMessageStatus.SIM_MESSAGE_STATUS_READ
}; };
sms.addSimMessage(simMessageOptions, (err, data) => { sms.addSimMessage(simMessageOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
...@@ -502,10 +502,10 @@ Adds a SIM message. This API uses a promise to return the result. ...@@ -502,10 +502,10 @@ Adds a SIM message. This API uses a promise to return the result.
```js ```js
let simMessageOptions = { let simMessageOptions = {
slotId = 0, slotId: 0,
smsc = "test", smsc: "test",
pdu = "xxxxxx", pdu: "xxxxxx",
status = 0 status: sms.SimMessageStatus.SIM_MESSAGE_STATUS_READ
}; };
let promise = sms.addSimMessage(simMessageOptions); let promise = sms.addSimMessage(simMessageOptions);
promise.then(data => { promise.then(data => {
...@@ -607,9 +607,9 @@ Updates a SIM message. This API uses an asynchronous callback to return the resu ...@@ -607,9 +607,9 @@ Updates a SIM message. This API uses an asynchronous callback to return the resu
```js ```js
let updateSimMessageOptions = { let updateSimMessageOptions = {
slotId = 0, slotId: 0,
msgIndex = 1, msgIndex: 1,
newStatus = 0, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE,
pdu = "xxxxxxx", pdu = "xxxxxxx",
smsc = "test" smsc = "test"
}; };
...@@ -647,9 +647,9 @@ Updates a SIM message. This API uses a promise to return the result. ...@@ -647,9 +647,9 @@ Updates a SIM message. This API uses a promise to return the result.
```js ```js
let updateSimMessageOptions = { let updateSimMessageOptions = {
slotId = 0, slotId: 0,
msgIndex = 1, msgIndex: 1,
newStatus = 0, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE,
pdu = "xxxxxxx", pdu = "xxxxxxx",
smsc = "test" smsc = "test"
}; };
...@@ -749,10 +749,11 @@ Sets the cell broadcast configuration. This API uses an asynchronous callback to ...@@ -749,10 +749,11 @@ Sets the cell broadcast configuration. This API uses an asynchronous callback to
```js ```js
let cbConfigOptions = { let cbConfigOptions = {
slotId = 0, slotId: 0,
smsc = "test", enable: true,
pdu = "xxxxxxxx", startMessageId: 100,
status = 0 endMessageId: 200,
ranType: sms.RanType.TYPE_GSM
}; };
sms.setCBConfig(cbConfigOptions, (err, data) => { sms.setCBConfig(cbConfigOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
...@@ -788,13 +789,14 @@ Sets the cell broadcast configuration. This API uses a promise to return the res ...@@ -788,13 +789,14 @@ Sets the cell broadcast configuration. This API uses a promise to return the res
```js ```js
let cbConfigOptions = { let cbConfigOptions = {
slotId = 0, slotId: 0,
smsc = "test", enable: true,
pdu = "xxxxxxxx", startMessageId: 100,
status = 0 endMessageId: 200,
ranType: sms.RanType.TYPE_GSM
}; };
let promise = sms.setCBConfig(cbConfigOptions); let promise = sms.setCBConfig(cbConfigOptions);
promise.then(data => promise.then(data => {
console.log(`setCBConfig success, promise: data->${JSON.stringify(data)}`); console.log(`setCBConfig success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`setCBConfig failed, promise: err->${JSON.stringify(err)}`); console.error(`setCBConfig failed, promise: err->${JSON.stringify(err)}`);
...@@ -859,7 +861,7 @@ Obtains SMS message segment information. This API uses a promise to return the r ...@@ -859,7 +861,7 @@ Obtains SMS message segment information. This API uses a promise to return the r
```js ```js
let slotId = 0; let slotId = 0;
let promise = sms.getSmsSegmentsInfo(slotId, "message", false); let promise = sms.getSmsSegmentsInfo(slotId, "message", false);
promise.then(data => promise.then(data => {
console.log(`getSmsSegmentsInfo success, promise: data->${JSON.stringify(data)}`); console.log(`getSmsSegmentsInfo success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`getSmsSegmentsInfo failed, promise: err->${JSON.stringify(err)}`); console.error(`getSmsSegmentsInfo failed, promise: err->${JSON.stringify(err)}`);
...@@ -886,7 +888,7 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t ...@@ -886,7 +888,7 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t
```js ```js
sms.isImsSmsSupported((err, data) => { sms.isImsSmsSupported((err, data) => {
console.log(`callback: err->${JSON.(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1023,7 +1025,7 @@ Decodes MMS messages. This API uses a promise to return the result. ...@@ -1023,7 +1025,7 @@ Decodes MMS messages. This API uses a promise to return the result.
```js ```js
let mmsFilePathName = "filename"; let mmsFilePathName = "filename";
let promise = sms.getSmscAddr(mmsFilePathName); let promise = sms.decodeMms(mmsFilePathName);
promise.then(data => { promise.then(data => {
console.log(`decodeMms success, promise: data->${JSON.stringify(data)}`); console.log(`decodeMms success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
...@@ -1092,13 +1094,13 @@ Encodes MMS messages. This API uses a promise to return the result. ...@@ -1092,13 +1094,13 @@ Encodes MMS messages. This API uses a promise to return the result.
```js ```js
let mmsAcknowledgeInd = { let mmsAcknowledgeInd = {
transactionId = "100", transactionId: "100",
version = 0x10, version: sms.MmsVersionType.MMS_VERSION_1_0,
reportAllowed = 128 reportAllowed = sms.ReportType.MMS_YES
}; };
let mmsInformation = { let mmsInformation = {
messageType = 133, messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND,
mmsType = mmsAcknowledgeInd mmsType: mmsAcknowledgeInd
}; };
let promise = sms.encodeMms(mmsInformation); let promise = sms.encodeMms(mmsInformation);
promise.then(data => { promise.then(data => {
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
- [Graphics](subsystems/subsys-graphics-overview.md) - [Graphics](subsystems/subsys-graphics-overview.md)
- [Multimedia](subsystems/subsys-multimedia-camera-overview.md) - [Multimedia](subsystems/subsys-multimedia-camera-overview.md)
- [Utils](subsystems/subsys-utils-overview.md) - [Utils](subsystems/subsys-utils-overview.md)
- [AI Framework](subsystems/subsys-aiframework-guide.md) - [AI Framework](subsystems/subsys-ai-aiframework-devguide.md)
- [Data Management](subsystems/subsys-data-relational-database-overview.md) - [Data Management](subsystems/subsys-data-relational-database-overview.md)
- [Sensor](subsystems/subsys-sensor-overview.md) - [Sensor](subsystems/subsys-sensor-overview.md)
- [USB](subsystems/subsys-usbservice-overview.md) - [USB](subsystems/subsys-usbservice-overview.md)
......
...@@ -274,7 +274,7 @@ int32_t I3cTestRequestIbi(void) ...@@ -274,7 +274,7 @@ int32_t I3cTestRequestIbi(void)
} }
ret = I3cRequestIbi(i3cHandle, 0x3F, TestI3cIbiFunc, 16); ret = I3cRequestIbi(i3cHandle, 0x3F, TestI3cIbiFunc, 16);
if (ret != 0) { if (ret != 0) {
HDF_LOGE("%s: Requset IBI failed!", __func__); HDF_LOGE("%s: Request IBI failed!", __func__);
return -1; return -1;
} }
......
...@@ -25,10 +25,10 @@ struct MmcCntlrOps { ...@@ -25,10 +25,10 @@ struct MmcCntlrOps {
int32_t (*setSdioIrq)(struct MmcCntlr *cntlr, bool enable); int32_t (*setSdioIrq)(struct MmcCntlr *cntlr, bool enable);
int32_t (*hardwareReset)(struct MmcCntlr *cntlr); int32_t (*hardwareReset)(struct MmcCntlr *cntlr);
int32_t (*systemInit)(struct MmcCntlr *cntlr); int32_t (*systemInit)(struct MmcCntlr *cntlr);
int32_t (*setEnhanceSrobe)(struct MmcCntlr *cntlr, bool enable); int32_t (*setEnhanceStrobe)(struct MmcCntlr *cntlr, bool enable);
int32_t (*switchVoltage)(struct MmcCntlr *cntlr, enum MmcVolt volt); int32_t (*switchVoltage)(struct MmcCntlr *cntlr, enum MmcVolt volt);
bool (*devReadOnly)(struct MmcCntlr *cntlr); bool (*devReadOnly)(struct MmcCntlr *cntlr);
bool (*devPluged)(struct MmcCntlr *cntlr); bool (*devPlugged)(struct MmcCntlr *cntlr);
bool (*devBusy)(struct MmcCntlr *cntlr); bool (*devBusy)(struct MmcCntlr *cntlr);
int32_t (*tune)(struct MmcCntlr *cntlr, uint32_t cmdCode); int32_t (*tune)(struct MmcCntlr *cntlr, uint32_t cmdCode);
int32_t (*rescanSdioDev)(struct MmcCntlr *cntlr); int32_t (*rescanSdioDev)(struct MmcCntlr *cntlr);
...@@ -47,10 +47,10 @@ struct MmcCntlrOps { ...@@ -47,10 +47,10 @@ struct MmcCntlrOps {
| setSdioIrq | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**enable**: whether to enable Secure Digital Input Output (SDIO) interrupts.| HDF_STATUS| Enables or disables SDIO interrupts.| | setSdioIrq | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**enable**: whether to enable Secure Digital Input Output (SDIO) interrupts.| HDF_STATUS| Enables or disables SDIO interrupts.|
| hardwareReset | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Resets hardware.| | hardwareReset | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Resets hardware.|
| systemInit | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Performs system initialization.| | systemInit | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Performs system initialization.|
| setEnhanceSrobe | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**enable**: whether to enable the enhanced strobe feature.| HDF_STATUS| Sets the enhanced strobe feature.| | setEnhanceStrobe | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**enable**: whether to enable the enhanced strobe feature.| HDF_STATUS| Sets the enhanced strobe feature.|
| switchVoltage | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**volt**: voltage to set, which can be 3.3 V, 1.8 V, or 1.2 V.| HDF_STATUS| Sets the voltage.| | switchVoltage | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**volt**: voltage to set, which can be 3.3 V, 1.8 V, or 1.2 V.| HDF_STATUS| Sets the voltage.|
| devReadOnly | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is read-only.| | devReadOnly | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is read-only.|
| cardPluged | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is removed.| | cardPlugged | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is removed.|
| devBusy | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is being used.| | devBusy | **cntlr**: structure pointer to the MMC controller at the core layer.| Boolean value| Checks whether the device is being used.|
| tune | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**cmdCode**: command code of the uint32_t type.| HDF_STATUS| Tunes the oscillator circuit frequency.| | tune | **cntlr**: structure pointer to the MMC controller at the core layer.<br>**cmdCode**: command code of the uint32_t type.| HDF_STATUS| Tunes the oscillator circuit frequency.|
| rescanSdioDev | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Scans and adds an SDIO device.| | rescanSdioDev | **cntlr**: structure pointer to the MMC controller at the core layer.| HDF_STATUS| Scans and adds an SDIO device.|
...@@ -254,7 +254,7 @@ The following uses **himci.c** as an example to present the information required ...@@ -254,7 +254,7 @@ The following uses **himci.c** as an example to present the information required
uint32_t maxBlkNum; uint32_t maxBlkNum;
uint32_t maxBlkSize; uint32_t maxBlkSize;
uint32_t maxReqSize; uint32_t maxReqSize;
bool devPluged; bool devPlugged;
bool detecting; bool detecting;
void *priv; void *priv;
}; };
...@@ -273,10 +273,10 @@ The following uses **himci.c** as an example to present the information required ...@@ -273,10 +273,10 @@ The following uses **himci.c** as an example to present the information required
.setSdioIrq = HimciSetSdioIrq, .setSdioIrq = HimciSetSdioIrq,
.hardwareReset = HimciHardwareReset, .hardwareReset = HimciHardwareReset,
.systemInit = HimciSystemInit, .systemInit = HimciSystemInit,
.setEnhanceSrobe= HimciSetEnhanceSrobe, .setEnhanceStrobe= HimciSetEnhanceStrobe,
.switchVoltage = HimciSwitchVoltage, .switchVoltage = HimciSwitchVoltage,
.devReadOnly = HimciDevReadOnly, .devReadOnly = HimciDevReadOnly,
.devPluged = HimciCardPluged, .devPlugged = HimciCardPlugged,
.devBusy = HimciDevBusy, .devBusy = HimciDevBusy,
.tune = HimciTune, .tune = HimciTune,
.rescanSdioDev = HimciRescanSdioDev, .rescanSdioDev = HimciRescanSdioDev,
......
...@@ -39,21 +39,7 @@ ...@@ -39,21 +39,7 @@
- [Utils Overview](subsys-utils-overview.md) - [Utils Overview](subsys-utils-overview.md)
- [Utils Development](subsys-utils-guide.md) - [Utils Development](subsys-utils-guide.md)
- [Utils FAQ](subsys-utils-faqs.md) - [Utils FAQ](subsys-utils-faqs.md)
- AI Framework - [AI Framework](subsys-ai-aiframework-devguide.md)
- [AI Engine Framework](subsys-aiframework-guide.md)
- [Development Environment](subsys-aiframework-envbuild.md)
- Technical Specifications
- [Code Management](subsys-aiframework-tech-codemanage.md)
- [Naming](subsys-aiframework-tech-name.md)
- [API Development](subsys-aiframework-tech-interface.md)
- Development Guidelines
- [SDK](subsys-aiframework-devguide-sdk.md)
- [Plug-in](subsys-aiframework-devguide-plugin.md)
- [Configuration File](subsys-aiframework-devguide-conf.md)
- Development Examples
- [KWS SDK](subsys-aiframework-demo-sdk.md)
- [KWS Plug-in](subsys-aiframework-demo-plugin.md)
- [KWS Configuration File](subsys-aiframework-demo-conf.md)
- Data Management - Data Management
- RDB - RDB
- [RDB Overview](subsys-data-relational-database-overview.md) - [RDB Overview](subsys-data-relational-database-overview.md)
...@@ -106,6 +92,7 @@ ...@@ -106,6 +92,7 @@
- [HiTraceChain Development](subsys-dfx-hitracechain.md) - [HiTraceChain Development](subsys-dfx-hitracechain.md)
- [HiCollie Development](subsys-dfx-hicollie.md) - [HiCollie Development](subsys-dfx-hicollie.md)
- HiSysEvent Development - HiSysEvent Development
- [HiSysEvent Overview](subsys-dfx-hisysevent-overview.md)
- [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md) - [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md)
- [HiSysEvent Logging](subsys-dfx-hisysevent-logging.md) - [HiSysEvent Logging](subsys-dfx-hisysevent-logging.md)
- [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md) - [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md)
......
# KWS Configuration File<a name="EN-US_TOPIC_0000001121062971"></a>
1. Add the KWS configuration file to the **//foundation/ai/engine/services/common/protocol/plugin\_config/plugin\_config\_ini/** directory.
```
[base]
supported_boards = hi3516dv300
related_sessions = asr_keyword_spotting+20001002
// Naming rule: [algorithm name+algorithm version], for example, [asr_keyword_spotting+20001002]
[asr_keyword_spotting+20001002]
AID = asr_keyword_spotting
VersionCode = 20001002
VersionName = 2.00.01.002
XPU = NNIE
District = China
// Location of the complied .so file of the plug-in
FullPath = /usr/lib/libasr_keyword_spotting.so
Chipset = ALL
ChkSum = ''
Key = ''
```
2. Add the type ID of the KWS algorithm to the **aie\_algorithm\_type.h** file in the **//foundation/ai/engine/services/common/protocol/plugin\_config/** directory.
```
// Make sure that the type ID maps to the sequence number in ALGORITHM_TYPE_ID_LITS.
const int ALGORITHM_TYPE_KWS = 3;
```
3. Add the name of the KWS algorithm and its sequence number in **ALGORITHM\_TYPE\_ID\_LITS** to the **aie\_plugin\_info.h** file in the **//foundation/ai/engine/services/server/plugin\_manager/include/** directory.
```
const std::string ALGORITHM_ID_SAMPLE_1 = "sample_plugin_1";
const std::string ALGORITHM_ID_SAMPLE_2 = "sample_plugin_2";
const std::string ALGORITHM_ID_IVP = "cv_human_detect";
// Add the name of the KWS algorithm: asr_keyword_spotting.
// Name the algorithm variable in the same way as the algorithm type ID in ALGORITHM_TYPE_ID_LIST, for example, ALGORITHM_ID_KWS.
const std::string ALGORITHM_ID_KWS = "asr_keyword_spotting";
const std::string ALGORITHM_ID_IC = "cv_image_classification";
const std::string ALGORITHM_ID_INVALID = "invalid algorithm id";
const std::vector<std::string> ALGORITHM_TYPE_ID_LIST = {
ALGORITHM_ID_SAMPLE_1,
ALGORITHM_ID_SAMPLE_2,
ALGORITHM_ID_IVP,
// Add the sequence number of the KWS algorithm to ALGORITHM_TYPE_ID_LITS, so that the name of the KWS algorithm can be obtained based on the sequence number.
// Make sure that the algorithm name maps to the sequence number in ALGORITHM_TYPE_ID_LITS.
ALGORITHM_ID_KWS,
ALGORITHM_ID_IC,
};
```
# KWS Plug-in<a name="EN-US_TOPIC_0000001090714913"></a>
1. Add the API of the KWS plug-in to the **//foundation/ai/engine/services/server/plugin** directory. This API is used to call AI capabilities. The following code snippet is an example API implementation of the KWS plug-in. The reference code is available at the **//foundation/ai/engine/services/server/plugin/asr/keyword\_spotting** directory.
```
#include "plugin/i_plugin.h
class KWSPlugin : public IPlugin {
public:
KWSPlugin();
~KWSPlugin();
const long long GetVersion() const override;
const char* GetName() const override;
const char* GetInferMode() const override;
int32_t Prepare(long long transactionId, const DataInfo &amp;amp;inputInfo, DataInfo &amp;amp;outputInfo) override;
int32_t SetOption(int optionType, const DataInfo &amp;amp;inputInfo) override;
int32_t GetOption(int optionType, const DataInfo &amp;amp;inputInfo, DataInfo &amp;amp;outputInfo) override;
int32_t SyncProcess(IRequest *request, IResponse *&amp;amp;response) override;
int32_t AsyncProcess(IRequest *request, IPluginCallback*callback) override;
int32_t Release(bool isFullUnload, long long transactionId, const DataInfo &amp;amp;inputInfo) override;
};
```
The preceding code implements the **IPlugin** API provided by the server. The following table shows the mapping between the client APIs and the plug-in APIs.
**Table 1** Mapping between the client APIs and the plug-in APIs
| Client API | Plug-in API | Description |
| ---------- | ----------- | ----------- |
| AieClientPrepare | Prepare | Initializes the inference algorithm plug-in. For KWS, this API loads the KWS model from the fixed location (/sdcard/wenwen_inst.wk) to the memory. |
| AieClientSyncProcess | SyncProcess | Executes the inference algorithm synchronously. For KWS, this API synchronously executes the audio inference algorithm to determine whether the specified wakeup keyword exists in the audio. |
| AieClientAsyncProcess | AsyncProcess | Executes the inference algorithm asynchronously. Currently, this API is not used in KWS. However, you can implement the API based on your use case. |
| AieClientSetOption | SetOption | Sets algorithm-related configuration items, such as the confidence threshold and delay. Currently, this API is not used in KWS. However, you can implement the API based on your use case. |
| AieClientGetOption | GetOption | Obtains algorithm-related configuration items. For KWS, this API can obtain the input and output scale of the KWS model. The input scale is the MFCC feature (fixed value: 4000) required by the KWS model, and the output scale is the confidence (fixed value: 2) of the result. |
| AieClientRelease | Release | Releases the algorithm model. For KWS, this API releases the specified algorithm model and clears the dynamic memory in the feature processor. |
>![](../public_sys-resources/icon-note.gif)**NOTE**
>- The **AieClientInit** and **AieClientDestroy** APIs are used to connect to and disconnect from the server, respectively. They are not called in the plug-in algorithm and therefore do not need to be defined in the plug-in.
>- The KWS plug-in needs to use the **PLUGIN\_INTERFACE\_IMPL** statement to expose the function pointer. Otherwise, the plug-in cannot be properly loaded.
```
PLUGIN_INTERFACE_IMPL(KWSPlugin);
```
\ No newline at end of file
# KWS SDK<a name="EN-US_TOPIC_0000001090776709"></a>
1. Add the API of the KWS SDK to the **//foundation/ai/engine /interfaces/kits** directory. This API can be called by third-party applications. The following code snippet is an example API for the KWS SDK. The reference code is available at the **//foundation/ai/engine /interfaces/kits/asr/keyword\_spotting** directory.
```
class KWSSdk {
public:
KWSSdk();
virtual ~KWSSdk();
// Create a KWS SDK instance.
int32_t Create();
// Synchronously execute the KWS task.
int32_t SyncExecute(const Array<int16_t> &audioInput);
// Set the KWS callback.
int32_t SetCallback(const std::shared_ptr<KWSCallback> &callback);
// Destroy the KWS SDK instance to release the session engaged with the plug-in.
int32_t Destroy();
};
```
2. Add the API implementation of the SDK to the **//foundation/ai/engine/services/client/algorithm\_sdk** directory and call the APIs provided by the client to use the algorithm plug-in capabilities. The following code snippet is an example implementation of the **create** method in the API of the KWS SDK. For more details, see the reference code at **//foundation/ai/engine/services/client/algorithm\_sdk/asr/keyword\_spotting**.
```
int32_t KWSSdk::KWSSdkImpl::Create()
{
if (kwsHandle_ != INVALID_KWS_HANDLE) {
HILOGE("[KWSSdkImpl]The SDK has been created");
return KWS_RETCODE_FAILURE;
}
if (InitComponents() != RETCODE_SUCCESS) {
HILOGE("[KWSSdkImpl]Fail to init sdk components");
return KWS_RETCODE_FAILURE;
}
// Call the AieClientInit API provided by the client to initialize the engine service and activate IPC call.
int32_t retCode = AieClientInit(configInfo_, clientInfo_, algorithmInfo_, nullptr);
if (retCode != RETCODE_SUCCESS) {
HILOGE("[KWSSdkImpl]AieClientInit failed. Error code[%d]", retCode);
return KWS_RETCODE_FAILURE;
}
if (clientInfo_.clientId == INVALID_CLIENT_ID) {
HILOGE("[KWSSdkImpl]Fail to allocate client id");
return KWS_RETCODE_FAILURE;
}
DataInfo inputInfo = {
.data = nullptr,
.length = 0,
};
DataInfo outputInfo = {
.data = nullptr,
.length = 0,
};
// Call the AieClientPrepare API provided by the client to load the algorithm plug-in.
retCode = AieClientPrepare(clientInfo_, algorithmInfo_, inputInfo, outputInfo, nullptr);
if (retCode != RETCODE_SUCCESS) {
HILOGE("[KWSSdkImpl]AieclientPrepare failed. Error code[%d]", retCode);
return KWS_RETCODE_FAILURE;
}
if (outputInfo.data == nullptr || outputInfo.length <= 0) {
HILOGE("[KWSSdkImpl]The data or length of output info is invalid");
return KWS_RETCODE_FAILURE;
}
MallocPointerGuard<unsigned char> pointerGuard(outputInfo.data);
retCode = PluginHelper::UnSerializeHandle(outputInfo, kwsHandle_);
if (retCode != RETCODE_SUCCESS) {
HILOGE("[KWSSdkImpl]Get handle from inputInfo failed");
return KWS_RETCODE_FAILURE;
}
return KWS_RETCODE_SUCCESS;
}
```
The preceding code is the specific API implementation. The **create** function in the API of the KWS SDK calls the open **AieClientInit** and **AieClientPrepare** APIs provided by the client to connect to the server and load the algorithm model. For details, see the implementation of the **create** method in following sections.
>![](../public_sys-resources/icon-note.gif) **NOTE**
>
>The sequence for the SDK to call client APIs: **AieClientInit** -\> **AieClientPrepare** -\> **AieClientSyncProcess** or **AieClientAsyncProcess** -\> **AieClientRelease** -\> **AieClientDestroy**. An exception will be thrown if the call sequence is violated.
# Development Examples<a name="EN-US_TOPIC_0000001077767514"></a>
For your better understanding, a KWS application is used as an example to walk you through the development process. You can develop the KWS SDK and plug-in based on the AI engine framework on the Hi3516D V300 development board, compile an image for the new version, and burn the image into the version. Then, develop an application with the KWS function. The application can receive external audio and pass the audio to the SDK API. If the audio contains specified keywords, the application will be able to recognize these keywords and print them in the command line.
This example uses a fixed keyword **Hi, xiaowen** for illustration. If the input audio contains **Hi, xiaowen**, the application prints **\[Hi, xiaowen\]**; otherwise, the application prints **\[UNKNOWN\]**.
- **[KWS SDK](subsys-aiframework-demo-sdk.md)**
- **[KWS Plug-in](subsys-aiframework-demo-plugin.md)**
- **[KWS Configuration File](subsys-aiframework-demo-conf.md)**
# Configuration File<a name="EN-US_TOPIC_0000001120666799"></a>
The SDK identifies the plug-in type based on **algorithmVersion** and **algorithmType** in the **AlgorithmInfo** structure so it can call the plug-in capabilities. Therefore, you need to develop the plug-in configuration file as follows:
1. Add the plug-in configuration file to the **//foundation/ai/engine/services/common/protocol/plugin\_config/plugin\_config\_ini/** directory.
2. Add the algorithm type to the **aie\_algorithm\_type.h** file in the **//foundation/ai/engine/services/common/protocol/plugin\_config/** directory.
3. Add the name of the KWS algorithm and its sequence number in **ALGORITHM\_TYPE\_ID\_LITS** to the **aie\_plugin\_info.h** file in the **//foundation/ai/engine/services/server/plugin\_manager/include/** directory.
For details about the development process, see the development example for the KWS configuration file.
# Development Guidelines<a name="EN-US_TOPIC_0000001090475723"></a>
To access the AI engine framework, you need to develop the SDKs and plug-ins shown in [Figure 1](subsys-aiframework-guide.md#fig143186187187). In this way, you can call the APIs provided by the SDKs to call the algorithm capabilities of plug-ins to implement lifecycle management and on-demand deployment of AI capabilities.
- **[SDK](subsys-aiframework-devguide-sdk.md)**
- **[Plug-in](subsys-aiframework-devguide-plugin.md)**
- **[Configuration File](subsys-aiframework-devguide-conf.md)**
# Development Environment<a name="EN-US_TOPIC_0000001077607540"></a>
1. Prepare development boards Hi3516D V300 and Hi3518E V300.
2. [Download the source code](../get-code/sourcecode-acquire.md).
# AI Engine Framework<a name="EN-US_TOPIC_0000001077309802"></a>
The AI subsystem of OpenHarmony provides native distributed AI capabilities. At the heart of the subsystem is a unified AI engine framework, which implements quick integration of AI algorithm plug-ins. The framework consists of the plug-in management, module management, and communication management modules, fulfilling lifecycle management and on-demand deployment of AI algorithms. Plug-in management implements lifecycle management, on-demand deployment, and quick integration of AI algorithm plug-ins. Module management implements task scheduling and client instance management. Communication management implements inter-process communication \(IPC\) between the client and server and data transmission between the AI engine and plug-ins. Under this framework, AI algorithm APIs will be standardized to facilitate distributed calling of AI capabilities. In addition, unified inference APIs will be provided to adapt to different inference framework hierarchies. [Figure 1](#fig143186187187) shows the AI engine framework.
**Figure 1** AI engine framework<a name="fig143186187187"></a>
![](figure/en-us_image_0000001077727032.png)
# Code Management<a name="EN-US_TOPIC_0000001096216399"></a>
Code of the AI engine framework consists of three parts: **client**, **server**, and **common**. The client module provides the server connection management function. The northbound SDK needs to encapsulate and call the public APIs provided by the client in the algorithm's external APIs. The server module provides functions such as plug-in loading and task management. Plug-ins are integrated using the plug-in APIs provided by the server. The common module provides platform-related operation methods, engine protocols, and tool classes for other modules.
[Figure 1](#fig171811112818) shows the code dependency between modules of the AI engine framework.
**Figure 1** Code dependency<a name="fig171811112818"></a>
![](figure/code-dependency-(2).jpg)
## Recommendation: Develop plug-ins and northbound SDKs in the directories specified by the AI engine.<a name="section17176374131"></a>
In the overall planning of the AI engine framework, northbound SDKs are a part of the client, and plug-ins are called by the server and are considered a part of the server. Therefore, the following directories have been planned for plug-in and northbound SDK development in the AI engine framework:
- SDK code directory: //foundation/ai/engine/services/client/algorithm\_sdk
Examples:
//foundation/ai/engine/services/client/algorithm\_sdk/cv
//foundation/ai/engine/services/client/algorithm\_sdk/nlu
- Plug-in code directory: //foundation/ai/engine/services/server/plugin
Examples:
//foundation/ai/engine/services/server/plugin/cv
//foundation/ai/engine/services/server/plugin/nlu
## Rule: Store all external APIs provided by plug-ins in the **interfaces/kits** directory of the AI subsystem.<a name="section2551029111312"></a>
The AI subsystem exposes its capabilities through external APIs of northbound SDKs. According to API management requirements of OpenHarmony, store all external APIs of northbound SDKs in the **interfaces/kits** directory of the subsystem. Currently, the external APIs of plug-ins of the AI subsystem are stored in the following directory: **//foundation/ai/engine/interface/kits**. You can add a sub-directory for each newly added plug-in in this directory. For example, if you add a CV plug-in, then store its external APIs in the **//foundation/ai/engine/interfaces/kits/cv** directory.
## Rule: Make sure that plug-in compilation results are stored in the **/usr/lib** directory.<a name="section97021558121310"></a>
Plug-in loading on the server uses the dlopen mode and can only be performed in the **/usr/lib** directory. Therefore, when compiling the **.so** file of a plug-in, set the output directory as **/usr/lib** in the compilation configuration file.
# API Development<a name="EN-US_TOPIC_0000001096100171"></a>
## Rule: Encapsulate the external APIs provided by the client based on the algorithm call sequence. For the SDK of an asynchronous plug-in, implement the **IClientCb** callback API provided by the client.<a name="section15872017171616"></a>
The external APIs provided by the client of the AI engine include **AieClientInit**, **AieClientPrepare**, **AieClientSyncProcess**, **AieClientAsyncProcess**, **AieClientRelease**, **AieClientDestroy**, **AieClientSetOption**, and **AieClientGetOption**. The SDK needs to encapsulate at least the following five APIs in sequence: **AieClientInit**, **AieClientPrepare**, **AieClientSyncProcess** \(or **AieClientAsyncProcess**\), **AieClientRelease**, and **AieClientDestroy**. Otherwise, a call failure or memory leakage may occur. For example, if the **AieClientprepare** API is omitted during encapsulation, the server cannot load the plug-in. As a result, APIs that follow it cannot be called.
For an asynchronous plug-in, the SDK needs to implement the **IClientCb** API to receive the algorithm inference result from the client and return the result to the third-party caller.
## Rule: Save all common data related to client interaction in the SDK during API implementation.<a name="section011283741612"></a>
The client of the AI engine uses the singleton pattern for API implementation. If the client is connecting to multiple SDKs, each SDK needs to store all common data exchanged with the client so that they can connect to the server to perform operations such as task inference and return the result. Common data usually includes **clientInfo**, **algorithmInfo**, and **configInfo**, which are defined in the SDK's member variables.
## Recommendation: Enable the SDK to implement the **IServiceDeadCb** API defined by the client.<a name="section1199125331613"></a>
The processes running on the server are system resident processes. The server provides services for clients by way of system capabilities. The **IServiceDeadCb** API is called if a server process is abnormally killed. The SDK can implement related operations in this API, for example, stopping process call or restarting the server.
The following is an example of **IServiceDeadCb** API implementation:
```
class ServiceDeadCb : public IServiceDeadCb {
public:
ServiceDeadCb() = default;
~ServiceDeadCb() override = default;
void OnServiceDead() override
{
printf("[ServiceDeadCb]OnServiceDead Callback happens");
}
};
```
As shown above, the SDK can implement its own operations in the **OnServiceDead\(\)** function, for example, stopping API call.
## Rule: Convert dedicated algorithm data into common data of the AI engine if the SDK and plug-ins need to use the codec module.<a name="section93139389171"></a>
For plug-ins, inference data is transmitted by the third-party caller to them through the client and server. The required data type varies according to algorithms. For example, the CV algorithm requires image data, and the ASR algorithm requires audio data. To address this issue, the AI engine provides the codec capabilities to convert different types of data into common data that can be used by it.
The encoded data is as follows:
```
struct DataInfo {
unsigned char *data;
int length;
} DataInfo;
```
As shown above, **DataInfo** consists of two variables: a pointer to the data memory, and the data length.
To use the APIs of the AI engine framework, you need to:
1. Add the dependency header file **utils/encdec/include/encdec.h**.
2. Add the dependency items in the **build.gn** file.
Add **"//foundation/ai/engine/services/common"** to **include\_dirs**.
Add **"//foundation/ai/engine/services/common/utils/encdec:encdec"** to **deps**.
3. Convert different types of data through codec. The following is an example:
```
// Example function for encoding: arg1, arg2, and arg3 are variables to be encoded, and dataInfo is the encoding result.
retCode = ProcessEncode(dataInfo, arg1, arg2, arg3) // The number of parameters can be flexible.
// Example function for decoding: dataInfo is the data to be decoded, and arg1, arg2, and arg3 are the decoding result.
retCode = ProcessDecode(dataInfo, arg1, arg2, arg3) // The number of parameters can be flexible.
```
Note:
- The sequence of parameters must be the same during encoding and decoding.
- After encoding, the memory used by **dataInfo** needs to be manually released by the caller.
- The memory is managed and released separately on the server and the client.
- If a pointer contains the shared memory, no extra processing is required.
- If other types of pointers are used, you need to dereference them before using **ProcessEncode** or **ProcessDecode**.
- The codec module has not been adapted to the **class** data type and therefore it is not recommended.
## Rule: Release the memory used by the encoded or decoded parameters in the SDK. Otherwise, a memory leakage occurs.<a name="section1698441814183"></a>
Encoding is essentially a process of encapsulating different types of data in the same memory space and then encapsulating the start address and length of the memory into the body. The plug-in is unable to release the memory that has been allocated to output parameter data returned to the SDK through encoding. To obtain the data, the SDK first needs to release the memory.
The following is an example of releasing the memory:
```
DataInfo outputInfo = {
.data = nullptr,
.length = 0,
};
AieClientPrepare(clientInfo_, algorithmInfo_, inputInfo, outputInfo, nullptr);
if (outputInfo.data != nullptr) {
free(outputInfo.data);
outputInfo.data = nullptr;
outputInfo.length = 0;
}
```
## Rule: Enable plug-ins to implement the **IPlugin** API defined by the server and use the **PLUGIN\_INTERFACE\_IMPL** statement to provide the function pointer for external systems.<a name="section20850717196"></a>
The server manages a variety of plug-ins, and the API implementation logic varies according to plug-ins. To unify the plug-in loading process, the AI engine provides the **IPlugin** API. In the runtime environment, a plug-in is loaded as a dynamic link library \(DLL\) by the AI engine framework in dlopen mode. Therefore, the plug-in needs to use the **PLUGIN\_INTERFACE\_IMPL** statement to expose the function pointer. Otherwise, the plug-in cannot be properly loaded.
## Rule: Use the unified data channel provided by the AI engine for plug-ins.<a name="section1493821732019"></a>
The AI engine provides a unified data channel between the server and plug-ins to send inference requests from the SDK and returned results from plug-ins. Plug-ins need to obtain the request data and encapsulate the inference result over the data channel when calling the inference API.
The following is an example of using the data channel:
```
int SyncProcess(IRequest *request, IResponse *&response)
{
HILOGI("[IvpPlugin]Begin SyncProcess");
if (request == nullptr) {
HILOGE("[IvpPlugin]SyncProcess request is nullptr");
return RETCODE_NULL_PARAM;
}
DataInfo inputInfo = request->GetMsg();
if (inputInfo.data == nullptr) {
HILOGE("[IvpPlugin]InputInfo data is nullptr");
return RETCODE_NULL_PARAM;
}
...
response = IResponse::Create(request);
response->SetResult(outputInfo);
return RETCODE_SUCCESS;
}
```
In the example, the request and response are the data body sent over the data channel. The server encapsulates data in the request and sends it to the plug-in. After completing algorithm processing, the plug-in encapsulates the result into the response and returns it to the server over the data channel.
# Naming<a name="EN-US_TOPIC_0000001095816835"></a>
## Rule: Name an SDK in the format of **domain\_keyword<\_other information 1\_other information 2\_...\>\_sdk.so**.<a name="section62071110121516"></a>
You are advised to use the commonly known abbreviations for domains. For example, use **cv** for image and video, **asr** for voice recognition, and **translation** for text translation. Add one if there is no available abbreviation for a domain. Use keywords that accurately describe the algorithm capability of the plug-in. For example, use **keyword\_spotting** for wakeup keyword spotting \(KWS\). Add other information, such as the supported chip type and applicable region, between **keyword** and **sdk**, with each of them separated by an underscore \(\_\). Note that the name of a northbound SDK must end with **sdk**.
For example, if the SDK for the KWS plug-in supports only the Kirin 9000 chipset and is applicable only in China, then name the SDK as follows: **asr\_keyword\_spotting\_kirin9000\_china\_sdk.so**.
## Rule: Name a plug-in in the format of **domain\_keyword<\_other information 1\_other information 2\_...\>.so**.<a name="section1665562841519"></a>
Use the same naming rules as the SDK.
A plug-in maps to an SDK. Therefore, they have the same requirements for the domain, keyword, and other information in their names. The only difference is that the name of the SDK ends with **\_sdk** additionally. For example, if the plug-in is named **asr\_keyword\_spotting.so**, the corresponding northbound SDK is named **asr\_keyword\_spotting\_sdk.so**.
For example, if the SDK for the KWS plug-in supports only the Kirin 9000 chipset and is applicable only in China, then name the plug-in as follows: **asr\_keyword\_spotting\_kirin9000\_china.so**.
# Technical Specifications<a name="EN-US_TOPIC_0000001095956459"></a>
**Conventions**
**Rule**: a convention that must be observed
**Recommendation**: a convention that should be considered
- **[Code Management](subsys-aiframework-tech-codemanage.md)**
- **[Naming](subsys-aiframework-tech-name.md)**
- **[API Development](subsys-aiframework-tech-interface.md)**
# AI Framework<a name="EN-US_TOPIC_0000001157479361"></a>
- **[AI Engine Framework](subsys-aiframework-guide.md)**
- **[Development Environment](subsys-aiframework-envbuild.md)**
- **[Technical Specifications](subsys-aiframework-tech.md)**
- **[Development Guidelines](subsys-aiframework-devguide.md)**
- **[Development Examples](subsys-aiframework-demo.md)**
...@@ -7,15 +7,15 @@ HiSysEvent provides event logging APIs for OpenHarmony to record important infor ...@@ -7,15 +7,15 @@ HiSysEvent provides event logging APIs for OpenHarmony to record important infor
The key modules of HiSysEvent are described as follows: The key modules of HiSysEvent are described as follows:
- Event configuration: enables you to define HiSysEvent events in YAML files. - [HiSysEvent logging configuration](subsys-dfx-hisysevent-logging-config.md): enables you to define HiSysEvent events in YAML files.
- Trace point configuration: provides trace point APIs and supports flushing of HiSysEvent events to disks. - [HiSysEvent logging](subsys-dfx-hisysevent-logging.md): provides trace point APIs and supports flushing of HiSysEvent events to disks.
- Event subscription: provides APIs for you to subscribe to HiSysEvent events by event domain and event name. - [HiSysEvent listening](subsys-dfx-hisysevent-listening.md): provides APIs for you to subscribe to HiSysEvent events by event domain and event name.
- Event query: provides APIs for you to query HiSysEvent events by event domain and event name. - [HiSysEvent query](subsys-dfx-hisysevent-query.md): provides APIs for you to query HiSysEvent events by event domain and event name.
- Event debugging tool: allows you to subscribe to real-time HiSysEvent events and query historical HiSysEvent events. - [HiSysEvent tool](subsys-dfx-hisysevent-tool.md): allows you to subscribe to real-time HiSysEvent events and query historical HiSysEvent events.
## Reference ## Reference
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
OpenHarmony文档的著作权由OpenHarmony项目拥有。 OpenHarmony文档的著作权由OpenHarmony项目拥有。
OpenHarmony文档根据知识共享署名4.0 (Creative Commons Attribution 4.0,简称CC BY 4.0)国际公共许可协议进行版权许可。为了方便用户理解,您可以通过访问https://creativecommons.org/licenses/by/4.0/了解CC BY 4.0的概要。CC BY 4.0的完整协议内容您可以访问如下网址获取:https://creativecommons.org/licenses/by/4.0/legalcode OpenHarmony文档根据知识共享署名4.0 (Creative Commons Attribution 4.0,简称CC BY 4.0)国际公共许可协议进行版权许可。为了方便用户理解,您可以通过访问https://creativecommons.org/licenses/by/4.0/ 了解CC BY 4.0的概要。CC BY 4.0的完整协议内容您可以访问如下网址获取:https://creativecommons.org/licenses/by/4.0/legalcode
......
...@@ -433,7 +433,7 @@ export default { ...@@ -433,7 +433,7 @@ export default {
console.log('ServiceAbility want:' + JSON.stringify(want)); console.log('ServiceAbility want:' + JSON.stringify(want));
console.log('ServiceAbility want name:' + want.bundleName) console.log('ServiceAbility want name:' + want.bundleName)
} catch(err) { } catch(err) {
console.log("ServiceAbility error:" + err) console.log('ServiceAbility error:' + err)
} }
console.info('ServiceAbility onConnect end'); console.info('ServiceAbility onConnect end');
return new IdlTestImp('connect'); return new IdlTestImp('connect');
...@@ -455,13 +455,13 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -455,13 +455,13 @@ import featureAbility from '@ohos.ability.featureAbility';
function callbackTestIntTransaction(result: number, ret: number): void { function callbackTestIntTransaction(result: number, ret: number): void {
if (result == 0 && ret == 124) { if (result == 0 && ret == 124) {
console.log("case 1 success "); console.log('case 1 success');
} }
} }
function callbackTestStringTransaction(result: number): void { function callbackTestStringTransaction(result: number): void {
if (result == 0) { if (result == 0) {
console.log("case 2 success "); console.log('case 2 success');
} }
} }
...@@ -472,17 +472,17 @@ var onAbilityConnectDone = { ...@@ -472,17 +472,17 @@ var onAbilityConnectDone = {
testProxy.testStringTransaction('hello', callbackTestStringTransaction); testProxy.testStringTransaction('hello', callbackTestStringTransaction);
}, },
onDisconnect:function (elementName) { onDisconnect:function (elementName) {
console.log("onDisconnectService onDisconnect"); console.log('onDisconnectService onDisconnect');
}, },
onFailed:function (code) { onFailed:function (code) {
console.log("onDisconnectService onFailed"); console.log('onDisconnectService onFailed');
} }
}; };
function connectAbility: void { function connectAbility: void {
let want = { let want = {
"bundleName":"com.example.myapplicationidl", bundleName: 'com.example.myapplicationidl',
"abilityName": "com.example.myapplicationidl.ServiceAbility" abilityName: 'com.example.myapplicationidl.ServiceAbility'
}; };
let connectionId = -1; let connectionId = -1;
connectionId = featureAbility.connectAbility(want, onAbilityConnectDone); connectionId = featureAbility.connectAbility(want, onAbilityConnectDone);
...@@ -595,7 +595,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { ...@@ -595,7 +595,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _reply = new rpc.MessageParcel(); let _reply = new rpc.MessageParcel();
_data.writeInt(data); _data.writeInt(data);
this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) { this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) {
if (result.errCode === 0) { if (result.errCode == 0) {
let _errCode = result.reply.readInt(); let _errCode = result.reply.readInt();
if (_errCode != 0) { if (_errCode != 0) {
let _returnValue = undefined; let _returnValue = undefined;
...@@ -605,7 +605,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { ...@@ -605,7 +605,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _returnValue = result.reply.readInt(); let _returnValue = result.reply.readInt();
callback(_errCode, _returnValue); callback(_errCode, _returnValue);
} else { } else {
console.log("sendRequest failed, errCode: " + result.errCode); console.log('sendRequest failed, errCode: ' + result.errCode);
} }
}) })
} }
...@@ -617,11 +617,11 @@ export default class IdlTestServiceProxy implements IIdlTestService { ...@@ -617,11 +617,11 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _reply = new rpc.MessageParcel(); let _reply = new rpc.MessageParcel();
_data.writeString(data); _data.writeString(data);
this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) { this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) {
if (result.errCode === 0) { if (result.errCode == 0) {
let _errCode = result.reply.readInt(); let _errCode = result.reply.readInt();
callback(_errCode); callback(_errCode);
} else { } else {
console.log("sendRequest failed, errCode: " + result.errCode); console.log('sendRequest failed, errCode: ' + result.errCode);
} }
}) })
} }
...@@ -644,12 +644,12 @@ import nativeMgr from 'nativeManager'; ...@@ -644,12 +644,12 @@ import nativeMgr from 'nativeManager';
function testIntTransactionCallback(errCode: number, returnValue: number) function testIntTransactionCallback(errCode: number, returnValue: number)
{ {
console.log("errCode: " + errCode + " returnValue: " + returnValue); console.log('errCode: ' + errCode + ' returnValue: ' + returnValue);
} }
function testStringTransactionCallback(errCode: number) function testStringTransactionCallback(errCode: number)
{ {
console.log("errCode: " + errCode); console.log('errCode: ' + errCode);
} }
function jsProxyTriggerCppStub() function jsProxyTriggerCppStub()
...@@ -660,6 +660,6 @@ function jsProxyTriggerCppStub() ...@@ -660,6 +660,6 @@ function jsProxyTriggerCppStub()
tsProxy.testIntTransaction(10, testIntTransactionCallback); tsProxy.testIntTransaction(10, testIntTransactionCallback);
// invoke testStringTransaction // invoke testStringTransaction
tsProxy.testStringTransaction("test", testIntTransactionCallback); tsProxy.testStringTransaction('test', testIntTransactionCallback);
} }
``` ```
...@@ -8,8 +8,8 @@ ...@@ -8,8 +8,8 @@
- 快速开始 - 快速开始
- 快速入门 - 快速入门
- [开发准备](quick-start/start-overview.md) - [开发准备](quick-start/start-overview.md)
- [使用eTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md) - [使用ArkTS语言开发(Stage模型)](quick-start/start-with-ets-stage.md)
- [使用eTS语言开发(FA模型)](quick-start/start-with-ets-fa.md) - [使用ArkTS语言开发(FA模型)](quick-start/start-with-ets-fa.md)
- [使用JS语言开发(FA模型)](quick-start/start-with-js-fa.md) - [使用JS语言开发(FA模型)](quick-start/start-with-js-fa.md)
- 开发基础知识 - 开发基础知识
- [应用包结构说明(FA模型)](quick-start/package-structure.md) - [应用包结构说明(FA模型)](quick-start/package-structure.md)
......
# 自动化测试框架使用指南
## 概述
为支撑OpenHarmony操作系统的自动化测试活动开展,我们提供了支持JS/TS语言的单元及UI测试框架,支持开发者针对应用接口或系统接口进行单元测试,并且可基于UI操作进行UI自动化脚本的编写。
本指南重点介绍自动化测试框架的主要功能,同时介绍编写单元/UI自动化测试脚本的方法以及执行过程。
### 简介
OpenHarmony自动化测试框架arkxtest,作为OpenHarmony工具集的重要组成部分,提供了OpenHarmony自动化脚本编写和运行的基础能力。编写方面提供了一系列支持测试脚本编写的API,包括了基础流程API、断言API以及UI操作相关的API,运行方面提供了识别测试脚本、调度执行测试脚本以及汇总测试脚本执行结果的能力。
### 实现原理
框架重要分为两大部分:单元测试框架和UI测试框架。
- 单元测试框架
单元测试框架是测试框架的基础底座,提供了最基本的用例识别、调度、执行及结果汇总的能力。主要功能如下图所示:
![](figures/UnitTest.PNG)
单元测试脚本的基础运行流程如下图所示,依赖aa test命令作为执行入口,该命令可具体参考[对应指南。](../ability/ability-delegator.md)
![](figures/TestFlow.PNG)
- UI测试框架
UI测试框架主要对外提供了[UiTest API](../reference/apis/js-apis-uitest.md)供开发人员在对应测试场景调用,而其脚本的运行基础还是上面提到的单元测试框架。
UI测试框架的主要功能如下图所示:
![](figures/Uitest.PNG)
### 约束与限制
- UI测试框架的能力在OpenHarmony 3.1 release版本之后方可使用,历史版本不支持使用。
- 单元测试框架的部分能力与其版本有关,具体能力与版本匹配信息可见代码仓中的[文档介绍](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_zh.md)
## 环境准备
### 环境要求
OpenHarmony自动化脚本的编写主要基于DevEco Studio,并建议使用3.0之后的版本进行脚本编写。
脚本执行需要PC连接OpenHarmony设备,如RK3568开发板等。
### 搭建环境
DevEco Studio可参考其官网介绍进行[下载](https://developer.harmonyos.com/cn/develop/deveco-studio#download),并进行相关的配置动作。
## 新建测试脚本
1. 在DevEco Studio中新建应用开发工程,其中ohos目录即为测试脚本所在的目录。
2. 在工程目录下打开待测试模块下的ets文件,将光标置于代码中任意位置,单击**右键 > Show Context Actions** **> Create Ohos Test**或快捷键**Alt+enter** **> Create Ohos Test**创建测试类,更多指导请参考DevEco Studio中[指导](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001267284568)
## 编写单元测试脚本
```TS
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
const delegator = abilityDelegatorRegistry.getAbilityDelegator()
export default function abilityTest() {
describe('ActsAbilityTest', function () {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
})
done();
})
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
})
}
```
单元测试脚本需要包含如下基本元素:
1、依赖导包,以便使用依赖的测试接口。
2、测试代码编写,主要编写测试代码的相关逻辑,如接口调用等。
3、断言接口调用,设置测试代码中的检查点,如无检查点,则不可认为一个完整的测试脚本。
## 编写UI测试脚本
UI测试脚本是在单元测试框架的基础上编写,主要就是增加了UI测试框架提供的接口调用,实现对应的测试逻辑。
下面的示例代码是在上面的测试脚本基础上增量编写,首先需要增加依赖导包,如下示例代码所示:
```js
import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest'
```
然后是具体测试代码编写,场景较为简单,就是在启动的应用页面上进行点击操作,然后增加检查点检查用例。
```js
export default function abilityTest() {
describe('ActsAbilityTest', function () {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
})
//ui test code
//init uidriver
var driver = await UiDriver.create();
await driver.delayMs(1000);
//find button by text 'Next'
var button = await driver.findComponent(BY.text('Next'));
//click button
await button.click();
await driver.delayMs(1000);
//check text
await driver.assertComponentExist(BY.text('after click'));
await driver.pressBack();
done();
})
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
})
}
```
## 执行测试脚本
执行测试脚本可以直接在DevEco Studio中通过点击按钮执行,当前支持以下执行方式:
1、测试包级别执行即执行测试包内的全部用例。
2、测试套级别执行即执行describe方法中定义的全部测试用例。
3、测试方法级别执行即执行指定it方法也就是单条测试用例。
![](figures/Execute.PNG)
## 查看测试结果
测试执行完毕后可直接在DevEco Studio中查看测试结果,如下图示例所示:
![](figures/TestResult.PNG)
# 音频播放开发指导 # 音频播放开发指导
## 场景介绍 ## 简介
音频播放的主要工作是将音频数据转码为可听见的音频模拟信号并通过输出设备进行播放,同时对播放任务进行管理 音频播放的主要工作是将音频数据转码为可听见的音频模拟信号,并通过输出设备进行播放,同时对播放任务进行管理,包括开始播放、暂停播放、停止播放、释放资源、设置音量、跳转播放位置、获取轨道信息等功能控制
**图1** 音频播放状态机 ## 运作机制
该模块提供了音频播放状态变化示意图和音频播放外部模块交互图。
**图1** 音频播放状态变化示意图
![zh-ch_image_audio_state_machine](figures/zh-ch_image_audio_state_machine.png) ![zh-ch_image_audio_state_machine](figures/zh-ch_image_audio_state_machine.png)
**说明**:当前为Idle状态,设置src不会改变状态;且src设置成功后,不能再次设置其它src,需调用reset()接口后,才能重新设置src。 **注意**:当前为Idle状态,设置src不会改变状态;且src设置成功后,不能再次设置其它src,需调用reset()接口后,才能重新设置src。
**图2** 音频播放零层 **图2** 音频播放外部模块交互
![zh-ch_image_audio_player](figures/zh-ch_image_audio_player.png) ![zh-ch_image_audio_player](figures/zh-ch_image_audio_player.png)
## 开发步骤 **说明**:三方应用通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件,将软件解码后的音频数据输出至硬件接口层的音频HDI,实现音频播放功能。
## 开发指导
详细API含义可参考:[媒体服务API文档AudioPlayer](../reference/apis/js-apis-media.md#audioplayer) 详细API含义可参考:[媒体服务API文档AudioPlayer](../reference/apis/js-apis-media.md#audioplayer)
### 全流程场景 ### 全流程场景
包含流程:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。 音频播放的全流程场景包含:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。
AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../reference/apis/js-apis-media.md#audioplayer_属性) AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../reference/apis/js-apis-media.md#audioplayer_属性)
......
# 音频录制开发指导 # 音频录制开发指导
## 场景介绍 ## 简介
音频录制的主要工作是捕获音频信号,完成音频编码并保存到文件中,帮助开发者轻松实现音频录制功能。它允许调用者指定音频录制的采样率、声道数、编码格式、封装格式、文件路径等参数。 音频录制的主要工作是捕获音频信号,完成音频编码并保存到文件中,帮助开发者轻松实现音频录制功能。该模块允许调用者指定音频录制的采样率、声道数、编码格式、封装格式、输出文件的路径等参数。
**图1** 音频录制状态机 ## 运作机制
该模块提供了音频录制状态变化示意图和音频录制外部模块交互图。
**图1** 音频录制状态变化变化示意图
![zh-ch_image_audio_recorder_state_machine](figures/zh-ch_image_audio_recorder_state_machine.png) ![zh-ch_image_audio_recorder_state_machine](figures/zh-ch_image_audio_recorder_state_machine.png)
**图2** 音频录制零层 **图2** 音频录制外部模块交互
![zh-ch_image_audio_recorder_zero](figures/zh-ch_image_audio_recorder_zero.png) ![zh-ch_image_audio_recorder_zero](figures/zh-ch_image_audio_recorder_zero.png)
## 开发步骤 **说明**:三方录音应用或录音机通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件获取通过音频HDI捕获的音频数据,再通过软件编码输出编码封装后的音频数据保存至文件中,实现音频录制功能。
## 约束与限制
开发者在进行录制功能开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE),权限配置相关内容可参考:[访问控制权限申请指导](../security/accesstoken-guidelines.md)
## 开发指导
详细API含义可参考:[媒体服务API文档AudioRecorder](../reference/apis/js-apis-media.md#audiorecorder) 详细API含义可参考:[媒体服务API文档AudioRecorder](../reference/apis/js-apis-media.md#audiorecorder)
### 全流程场景 ### 全流程场景
包含流程:创建实例,设置录制参数,录制音频,暂停录制,恢复录制,停止录制,释放资源等流程。 音频录制的全流程场景包含:创建实例,设置录制参数,开始录制,暂停录制,恢复录制,停止录制,释放资源等流程。
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
......
# 视频播放开发指导 # 视频播放开发指导
## 场景介绍 ## 简介
视频播放的主要工作是将视频数据转码并输出到设备进行播放,同时管理播放任务。本文将对视频播放全流程、视频切换、视频循环播放等场景开发进行介绍说明。 视频播放的主要工作是将视频数据转码并输出到设备进行播放,同时管理播放任务,包括开始播放、暂停播放、停止播放、资源释放、音量设置、跳转播放位置、设置倍数、获取轨道信息等功能控制。本文将对视频播放全流程、视频切换、视频循环播放等场景开发进行介绍说明。
**图1** 视频播放状态机 ## 运作机制
该模块提供了视频播放状态变化示意图和视频播放外部模块交互图。
**图1** 视频播放状态变化示意图
![zh-ch_image_video_state_machine](figures/zh-ch_image_video_state_machine.png) ![zh-ch_image_video_state_machine](figures/zh-ch_image_video_state_machine.png)
**图2** 视频播放零层 **图2** 视频播放外部模块交互
![zh-ch_image_video_player](figures/zh-ch_image_video_player.png) ![zh-ch_image_video_player](figures/zh-ch_image_video_player.png)
**说明**:三方应用通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件将软件解码后的音频数据,输出至音频HDI,和图形子系统将硬件接口层的解码HDI部件的解码后的图像数据,输出至显示HDI,实现视频播放功能。
*注意:视频播放需要显示、音频、编解码等硬件能力。* *注意:视频播放需要显示、音频、编解码等硬件能力。*
1. 三方应用从Xcomponent组件获取surfaceID。 1. 三方应用从Xcomponent组件获取surfaceID。
...@@ -31,13 +37,13 @@ ...@@ -31,13 +37,13 @@
| ts | 视频格式:H264/MPEG2/MPEG4 音频格式:AAC/MP3 | 主流分辨率,如1080P/720P/480P/270P | | ts | 视频格式:H264/MPEG2/MPEG4 音频格式:AAC/MP3 | 主流分辨率,如1080P/720P/480P/270P |
| webm | 视频格式:VP8 音频格式:VORBIS | 主流分辨率,如1080P/720P/480P/270P | | webm | 视频格式:VP8 音频格式:VORBIS | 主流分辨率,如1080P/720P/480P/270P |
## 开发步骤 ## 开发指导
详细API含义可参考:[媒体服务API文档VideoPlayer](../reference/apis/js-apis-media.md#videoplayer8) 详细API含义可参考:[媒体服务API文档VideoPlayer](../reference/apis/js-apis-media.md#videoplayer8)
### 全流程场景 ### 全流程场景
包含流程:创建实例,设置url,设置SurfaceId,准备播放视频,播放视频,暂停播放,获取轨道信息,跳转播放位置,设置音量,设置倍速,结束播放,重置,释放资源等流程。 视频播放的全流程场景包含:创建实例,设置url,设置SurfaceId,准备播放视频,播放视频,暂停播放,获取轨道信息,跳转播放位置,设置音量,设置倍速,结束播放,重置,释放资源等流程。
VideoPlayer支持的url媒体源输入类型可参考:[url属性说明](../reference/apis/js-apis-media.md#videoplayer_属性) VideoPlayer支持的url媒体源输入类型可参考:[url属性说明](../reference/apis/js-apis-media.md#videoplayer_属性)
......
# 视频录制开发指导 # 视频录制开发指导
## 场景介绍 ## 简介
视频录制的主要工作是捕获音视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。 视频录制的主要工作是捕获音视频信号,完成音视频编码并保存到文件中,帮助开发者轻松实现音视频录制功能,包括开始录制、暂停录制、恢复录制、停止录制、释放资源等功能控制。它允许调用者指定录制的编码格式、封装格式、文件路径等参数。
**图1** 视频录制状态机 ## 运作机制
该模块提供了视频录制状态变化示意图和视频录制外部模块交互图。
**图1** 视频录制状态变化示意图
![zh-ch_image_video_recorder_state_machine](figures/zh-ch_image_video_recorder_state_machine.png) ![zh-ch_image_video_recorder_state_machine](figures/zh-ch_image_video_recorder_state_machine.png)
**图2** 视频录制零层 **图2** 视频录制外部模块交互
![zh-ch_image_video_recorder_zero](figures/zh-ch_image_video_recorder_zero.png) ![zh-ch_image_video_recorder_zero](figures/zh-ch_image_video_recorder_zero.png)
## 开发步骤 **说明**:三方相机应用或系统相机通过调用JS接口层提供的js接口实现相应功能时,框架层会通过Native Framework的媒体服务,调用音频部件通过音频HDI捕获的音频数据,再通过软件编码输出编码封装后的音频数据保存至文件中,和图形子系统通过视频HDI捕获的图像数据,再通过视频编码HDI编码,将编码后的图像数据保存至文件中,实现视频录制功能。
## 约束与限制
开发者在进行录制功能开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE)和相机权限(ohos.permission.CAMERA),权限配置相关内容可参考:[访问控制权限申请指导](../security/accesstoken-guidelines.md)
## 开发指导
详细API含义可参考:[媒体服务API文档VideoRecorder](../reference/apis/js-apis-media.md#videorecorder9) 详细API含义可参考:[媒体服务API文档VideoRecorder](../reference/apis/js-apis-media.md#videorecorder9)
### 全流程场景 ### 全流程场景
包含流程:创建实例、设置录制参数、录制视频、暂停录制、恢复录制、停止录制、释放资源等流程。 视频录制全流程场景包含:创建实例、设置录制参数、开始录制、暂停录制、恢复录制、停止录制、释放资源等流程。
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
......
...@@ -3,7 +3,4 @@ ...@@ -3,7 +3,4 @@
- [公共事件与通知概述](notification-brief.md) - [公共事件与通知概述](notification-brief.md)
- [公共事件开发指导](common-event.md) - [公共事件开发指导](common-event.md)
- [通知开发指导](notification-guidelines.md) - [通知开发指导](notification-guidelines.md)
- 后台代理提醒
- [后台代理提醒开发概述](background-agent-scheduled-reminder-overview.md)
- [后台代理提醒开发指导](background-agent-scheduled-reminder-guide.md)
- [调试助手使用指导](assistant-guidelines.md) - [调试助手使用指导](assistant-guidelines.md)
\ No newline at end of file
...@@ -32,7 +32,8 @@ import commonEvent from '@ohos.commonEvent'; ...@@ -32,7 +32,8 @@ import commonEvent from '@ohos.commonEvent';
2. 创建订阅者信息,详细的订阅者信息数据类型及包含的参数请见[CommonEventSubscribeInfo文档](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo)介绍。 2. 创建订阅者信息,详细的订阅者信息数据类型及包含的参数请见[CommonEventSubscribeInfo文档](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo)介绍。
```js ```js
private subscriber = null //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
private subscriber = null
//订阅者信息 //订阅者信息
var subscribeInfo = { var subscribeInfo = {
......
# 公共事件与通知开发概述 # 公共事件与通知开发概述
公共事件与通知提供了应用程序向系统其他应用程序发布消息、接收来自系统或其他应用特定消息的能力,这些消息可以是新闻推送、广告通知或者预警信息。 公共事件与通知提供了应用程序向系统其他应用程序发布消息、接收来自系统或其他应用特定消息的能力,这些消息可以是新闻推送、广告通知或者预警信息
CES(Common Event Service, 即公共事件服务)为应用程序提供发布、订阅及退订公共事件的能力。公共事件根据事件发送方不同可分为系统公共事件和自定义公共事件。 CES(Common Event Service, 即公共事件服务)为应用程序提供发布、订阅及退订公共事件的能力。公共事件根据事件发送方不同可分为系统公共事件和自定义公共事件。
...@@ -9,7 +9,7 @@ CES(Common Event Service, 即公共事件服务)为应用程序提供发布 ...@@ -9,7 +9,7 @@ CES(Common Event Service, 即公共事件服务)为应用程序提供发布
- 系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户程序。 公共事件包括:终端设备用户可感知的亮灭屏事件,以及系统关键服务发布的系统事件(例如:USB插拔,网络连接,系统升级)等。 - 系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户程序。 公共事件包括:终端设备用户可感知的亮灭屏事件,以及系统关键服务发布的系统事件(例如:USB插拔,网络连接,系统升级)等。
- 自定义公共事件:由应用自身定义的期望特定订阅者可以接收到的公共事件,这些公共事件往往与应用自身的业务逻辑相关。 - 自定义公共事件:由应用自身定义的期望特定订阅者可以接收到的公共事件,这些公共事件往往与应用自身的业务逻辑相关。
ANS(Advanced Notification Service,即通知增强服务)为应用程序提供发布通知的能力。这些通知常见的使用场景如下: ANS(Advanced Notification Service,即通知系统服务)为应用程序提供发布通知的能力。这些通知常见的使用场景如下:
- 显示接收到的短消息、即时通讯消息等; - 显示接收到的短消息、即时通讯消息等;
- 显示应用的推送消息,如广告、版本更新、新闻通知等; - 显示应用的推送消息,如广告、版本更新、新闻通知等;
......
...@@ -2,11 +2,24 @@ ...@@ -2,11 +2,24 @@
- 快速入门 - 快速入门
- [开发准备](start-overview.md) - [开发准备](start-overview.md)
- [使用eTS语言开发(Stage模型)](start-with-ets-stage.md) - [使用ArkTS语言开发(Stage模型)](start-with-ets-stage.md)
- [使用eTS语言开发(FA模型)](start-with-ets-fa.md) - [使用ArkTS语言开发(FA模型)](start-with-ets-fa.md)
- [使用JS语言开发(FA模型)](start-with-js-fa.md) - [使用JS语言开发(FA模型)](start-with-js-fa.md)
- 开发基础知识 - 开发基础知识
- [应用包结构说明(FA模型)](package-structure.md) - [应用包结构说明(FA模型)](package-structure.md)
- [应用包结构说明(Stage模型)](stage-structure.md) - [应用包结构说明(Stage模型)](stage-structure.md)
- [SysCap说明](syscap.md) - [SysCap说明](syscap.md)
- [HarmonyAppProvision配置文件](app-provision-structure.md) - [HarmonyAppProvision配置文件](app-provision-structure.md)
\ No newline at end of file - 学习eTS语言
- [初识ets语言](ets-get-started.md)
- eTS语法(声明式UI)
- [基本UI描述](ets-basic-ui-description.md)
- 状态管理
- [基本概念](ets-state-mgmt-concepts.md)
- [页面级变量的状态管理](ets-state-mgmt-page-level.md)
- [应用级变量的状态管理](ets-state-mgmt-application-level.md)
- [动态构建UI元素](ets-dynamic-ui-elememt-building.md)
- [渲染控制](ets-rendering-control.md)
- [使用限制与扩展](ets-restrictions-and-extensions.md)
\ No newline at end of file
# 基本UI描述
eTS通过装饰器@Component和@Entry装饰struct关键字声明的数据结构,构成一个自定义组件。自定义组件中提供了一个build函数,开发者需在该函数内以链式调用的方式进行基本的UI描述,UI描述的方法请参考[UI描述规范](#ui描述规范)
## 基本概念
- struct:组件可以基于struct实现,不能有继承关系,对于struct的实例化,可以省略new。
- 装饰器:装饰器给被装饰的对象赋予某一种能力,其不仅可以装饰类或结构体,还可以装饰类的属性。多个装饰器可以叠加到目标元素,定义在同一行上或者多行上,推荐定义在多行上。
```ts
@Entry
@Component
struct MyComponent {
}
```
- build函数:自定义组件必须定义build函数,并且自定义组件禁止自定义构造函数。build函数满足Builder构造器接口定义,用于定义组件的声明式UI描述。
```ts
interface Builder {
build: () => void
}
```
- @Component:装饰struct,结构体在装饰后具有基于组件的能力,需要实现build方法来更新UI。
- @Entry: 装饰struct,组件被装饰后作为页面的入口,页面加载时将被渲染显示。
- @Preview:装饰struct, 用@Preview装饰的自定义组件可以在DevEco Studio的预览器上进行实时预览,加载页面时,将创建并呈现@Preview装饰的自定义组件。
> **说明:** 在单个源文件中,最多可以使用10个@Preview装饰自定义组件,更多说明请参考[查看eTS组件预览效果](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596#section146052489820)。
- 链式调用:以 "." 链式调用的方式配置UI结构及其属性、事件等。
## UI描述规范
### 无参数构造配置
组件的接口定义不包含必选构造参数,组件后面的“()”中不需要配置任何内容。例如,Divider组件不包含构造参数:
```ts
Column() {
Text('item 1')
Divider()
Text('item 2')
}
```
### 必选参数构造配置
如果组件的接口定义中包含必选构造参数,则在组件后面的“()”中必须配置参数,参数可以使用常量进行赋值。
例如:
- Image组件的必选参数src:
```ts
Image('http://xyz/a.jpg')
```
- Text组件的必选参数content:
```ts
Text('123')
```
变量或表达式也可以用于参数赋值,其中表达式返回的结果类型必须满足参数类型要求。例如,传递变量或表达式来构造Image和Text组件的参数:
```ts
Image(this.imagePath)
Image('http://' + this.imageUrl)
Text(`count: ${this.count}`)
```
### 属性配置
使用属性方法配置组件的属性,属性方法紧随组件,并用"."运算符连接。
- 配置Text组件的字体大小属性:
```ts
Text('123')
.fontSize(12)
```
- 使用"."操作进行链式调用并同时配置组件的多个属性,如下所示:
```ts
Image('a.jpg')
.alt('error.jpg')
.width(100)
.height(100)
```
- 除了直接传递常量参数外,还可以传递变量或表达式,如下所示:
```ts
Text('hello')
.fontSize(this.size)
Image('a.jpg')
.width(this.count % 2 === 0 ? 100 : 200)
.height(this.offset + 100)
```
- 对于系统内置组件,框架还为其属性预定义了一些[枚举类型](../reference/arkui-ts/ts-appendix-enums.md)供开发人员调用,枚举类型必须满足参数类型要求,枚举值可以作为参数传递。可以按以下方式配置Text组件的颜色和字体属性:
```ts
Text('hello')
.fontSize(20)
.fontColor(Color.Red)
.fontWeight(FontWeight.Bold)
```
### 事件配置
通过事件方法可以配置组件支持的事件。
- 使用lambda表达式配置组件的事件方法:
```ts
Button('add counter')
.onClick(() => {
this.counter += 2
})
```
- 使用匿名函数表达式配置组件的事件方法,要求使用bind,以确保函数体中的this引用包含的组件:
```ts
Button('add counter')
.onClick(function () {
this.counter += 2
}.bind(this))
```
- 使用组件的成员函数配置组件的事件方法:
```ts
myClickHandler(): void {
}
...
Button('add counter')
.onClick(this.myClickHandler)
```
### 子组件配置
对于支持子组件配置的组件,例如容器组件,在"{ ... }"里为组件添加子组件的UI描述。Column、Row、Stack、Button、Grid和List组件都是容器组件。
- 以下是简单的Column示例:
```ts
Column() {
Text('Hello')
.fontSize(100)
Divider()
Text(this.myText)
.fontSize(100)
.fontColor(Color.Red)
}
```
- 可以嵌套多个子组件:
```ts
Column() {
Column() {
Button() {
Text('+ 1')
}.type(ButtonType.Capsule)
.onClick(() => console.log ('+1 clicked!'))
Image('1.jpg')
}
Divider()
Column() {
Button() {
Text('+ 2')
}.type(ButtonType.Capsule)
.onClick(() => console.log ('+2 clicked!'))
Image('2.jpg')
}
Divider()
Column() {
Button() {
Text('+ 3')
}.type(ButtonType.Capsule)
.onClick(() => console.log('+3 clicked!'))
Image('3.jpg')
}
}.alignItems(HorizontalAlign.Center)
```
\ No newline at end of file
# 动态构建UI元素
前面章节介绍的是如何创建一个组件内部UI结构固定的自定义组件,为了满足开发者自定义组件内部UI结构的需求,eTS同时提供了动态构建UI元素的能力。
## @Builder
可通过@Builder装饰器进行描述,该装饰器可以修饰一个函数,此函数可以在build函数之外声明,并在build函数中或其他@Builder修饰的函数中使用,在一个自定义组件内快速生成多个布局内容。使用方式如下面示例所示。
```ts
// xxx.ets
@Component
struct CompB {
@State CompValue: string = '';
aboutToAppear() {
console.info('CompB aboutToAppear.');
}
aboutToDisappear() {
console.info('CompB aboutToDisappear.');
}
build() {
Column() {
Button(this.CompValue);
}
}
}
@Entry
@Component
struct CompA {
size1: number = 100;
@State CompValue1: string = "Hello,CompValue1";
@State CompValue2: string = "Hello,CompValue2";
@State CompValue3: string = "Hello,CompValue3";
// @Builder装饰的函数内使用自定义组件
@Builder CompC(value: string) {
CompB({ CompValue: value });
}
@Builder SquareText(label: string) {
Text(label)
.width(1 * this.size1)
.height(1 * this.size1)
}
@Builder RowOfSquareTexts(label1: string, label2: string) {
Row() {
this.SquareText(label1)
this.SquareText(label2)
}
.width(2 * this.size1)
.height(1 * this.size1)
}
build() {
Column() {
Row() {
this.SquareText("A")
this.SquareText("B")
// or as long as tsc is used
}
.width(2 * this.size1)
.height(1 * this.size1)
this.RowOfSquareTexts("C", "D")
Column() {
// 使用三次@Builder装饰的自定义组件
this.CompC(this.CompValue1);
this.CompC(this.CompValue2);
this.CompC(this.CompValue3);
}
.width(2 * this.size1)
.height(2 * this.size1)
}
.width(2 * this.size1)
.height(2 * this.size1)
}
}
```
## @BuilderParam<sup>8+<sup>
@BuilderParam装饰器用于修饰自定义组件内函数类型的属性(例如:`@BuilderParam content: () => any;`),并且在初始化自定义组件时被@BuilderParam修饰的属性必须赋值。
### 引入动机
当开发者创建自定义组件,想对该组件添加特定功能时(如:仅对自定义组件添加一个点击跳转操作)。若直接在组件内嵌入事件方法,将会导致所有初始化该组件的地方均增加了该功能。为解决此问题,引入了@BuilderParam装饰器,此装饰器修饰的属性值可为@Builder修饰的方法,开发者可在初始化自定义组件时对此属性进行赋值,为自定义组件增加特定的的功能。
### 参数初始化组件
通过参数初始化组件时,将@Builder装饰的方法赋值给@BuilderParam修饰的属性,并在自定义组件内调用content属性值。对@BuilderParam修饰的属性进行赋值时不带参数(如:`content: this.specificParam`),则此属性的类型需定义成无返回值的函数(如:`@BuilderParam content: () => void`)。若带参数(如:`callContent: this.specificParam1("111")`),则此属性的类型需定义成any(如:`@BuilderParam callContent: any;`)。
```ts
// xxx.ets
@Component
struct CustomContainer {
header: string = "";
@BuilderParam noParam: () => void;
@BuilderParam withParam: any;
footer: string = "";
build() {
Column() {
Text(this.header)
.fontSize(50)
this.noParam()
this.withParam()
Text(this.footer)
.fontSize(50)
}
}
}
@Entry
@Component
struct CustomContainerUser {
@Builder specificNoParam() {
Column() {
Text("noParam").fontSize(50)
}
}
@Builder SpecificWithParam(label: string) {
Column() {
Text(label).fontSize(50)
}
}
build() {
Column() {
CustomContainer({
header: "Header",
noParam: this.specificNoParam,
withParam: this.SpecificWithParam("WithParam"),
footer: "Footer",
})
}
}
}
```
### 尾随闭包初始化组件
在自定义组件中使用@BuilderParam修饰的属性接收尾随闭包(在初始化自定义组件时,组件名称紧跟一个大括号“{}”形成尾随闭包场景(`CustomComponent(){}`)。开发者可把尾随闭包看做一个容器,向其填充内容,如在闭包内增加组件(`{Column(){Text("content")}`),闭包内语法规范与build函数一致。此场景下自定义组件内有且仅有一个使用@BuilderParam修饰的属性。
示例:在闭包内增加Column组件并添加点击事件,在新增的Column组件内调用@Builder修饰的specificParam方法,点击Column组件后该改变自定义组件中header的属性值为“changeHeader”。并且在初始化自定义组件时会把尾随闭包的内容赋值给使用@BuilderParam修饰的closer属性。
```ts
// xxx.ets
@Component
struct CustomContainer {
header: string = "";
@BuilderParam closer: () => void;
build() {
Column() {
Text(this.header)
.fontSize(50)
this.closer()
}
}
}
@Builder function specificParam(label1: string, label2: string) {
Column() {
Text(label1)
.fontSize(50)
Text(label2)
.fontSize(50)
}
}
@Entry
@Component
struct CustomContainerUser {
@State text: string = "header"
build() {
Column() {
CustomContainer({
header: this.text,
}){
Column(){
specificParam("111", "22")
}.onClick(()=>{
this.text = "changeHeader"
})
}
}
}
}
```
## @Styles
eTS为了避免开发者对重复样式的设置,通过@Styles装饰器可以将多条样式设置提炼成一个方法,直接在组件声明的位置使用。@Styles装饰器将新的属性函数添加到基本组件上,如Text、Column、Button等。当前@Styles仅支持通用属性。通过@Styles装饰器可以快速定义并复用组件的自定义样式。
@Styles可以定义在组件内或组件外,在组件外定义时需在方法前添加function关键字,组件内定义时不需要添加function关键字。
```ts
// xxx.ets
@Styles function globalFancy() {
.backgroundColor(Color.Red)
}
@Entry
@Component
struct FancyUse {
@Styles componentFancy() {
.backgroundColor(Color.Blue)
}
build() {
Column({ space: 10 }) {
Text("Fancy")
.globalFancy()
.width(100)
.height(100)
.fontSize(30)
Text("Fancy")
.componentFancy()
.width(100)
.height(100)
.fontSize(30)
}
}
}
```
@Styles还可以在[StateStyles](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md)属性内部使用,在组件处于不同的状态时赋予相应的属性。
在StateStyles内可以直接调用组件外定义的Styles,但需要通过this关键字调用组件内定义的Styles。
```ts
// xxx.ets
@Styles function globalFancy() {
.width(100)
.height(100)
}
@Entry
@Component
struct FancyUse {
@Styles componentFancy() {
.width(50)
.height(50)
}
build() {
Row({ space: 10 }) {
Button() {
Text("Fancy")
}
.stateStyles({
normal: {
.width(80)
.height(80)
},
disabled: this.componentFancy,
pressed: globalFancy
})
}
}
}
```
## @Extend
@Extend装饰器将新的属性函数添加到内置组件上,如Text、Column、Button等。通过@Extend装饰器可以快速的扩展原生组件。@Extend装饰器不能用在自定义组件struct定义框内。
```ts
// xxx.ets
@Extend(Text) function fancy(fontSize: number) {
.fontColor(Color.Red)
.fontSize(fontSize)
.fontStyle(FontStyle.Italic)
}
@Entry
@Component
struct FancyUse {
build() {
Row({ space: 10 }) {
Text("Fancy")
.fancy(16)
Text("Fancy")
.fancy(24)
}
}
}
```
> **说明:**
>
> - @Extend装饰器不能用在自定义组件struct定义框内。
> - @Extend装饰器内仅支持属性函数语句。
## @CustomDialog
@CustomDialog装饰器用于装饰自定义弹窗,使得弹窗可以动态设置样式。
```ts
// custom-dialog-demo.ets
@CustomDialog
struct DialogExample {
controller: CustomDialogController;
action: () => void;
build() {
Row() {
Button ("Close CustomDialog")
.onClick(() => {
this.controller.close();
this.action();
})
}.padding(20)
}
}
@Entry
@Component
struct CustomDialogUser {
dialogController : CustomDialogController = new CustomDialogController({
builder: DialogExample({action: this.onAccept}),
cancel: this.existApp,
autoCancel: true
});
onAccept() {
console.log("onAccept");
}
existApp() {
console.log("Cancel dialog!");
}
build() {
Column() {
Button("Click to open Dialog")
.onClick(() => {
this.dialogController.open()
})
}
}
}
```
![custom-dialog-demo](figures/custom-dialog-demo.gif)
\ No newline at end of file
# 初识eTS语言
eTS(extended TypeScript)是OpenHarmony优选的主力应用开发语言。eTS基于TypeScript(简称TS)语言扩展而来,是TS的超集。
- eTS继承了TS的所有特性。
- 当前,eTS在TS基础上主要扩展了[声明式UI](ets-basic-ui-description.md)能力,让开发者以更简洁、更自然的方式开发高性能应用。
当前扩展的声明式UI包括如下特性。
- [基本UI描述](ets-basic-ui-description.md):eTS定义了各种装饰器、自定义组件、UI描述机制,再配合UI开发框架中的UI内置组件、事件方法、属性方法等共同构成了UI开发的主体。
- [状态管理](ets-state-mgmt-page-level.md):eTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之间,也可以是全局范围内的传递,还可以是 跨设备传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。
- [动态构建UI元素](ets-dynamic-ui-elememt-building.md):eTS提供了动态构建UI元素的能力,不仅可以自定义组件内部的UI结构,还可复用组件样式,扩展原生组件。
- [渲染控制](ets-rendering-control.md):eTS提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。
- [使用限制与扩展](ets-restrictions-and-extensions.md):eTS在使用过程中存在限制与约束,同时也扩展了双向绑定等能力。
- 未来,eTS会结合应用开发/运行的需求持续演进,逐步提供并行和并发能力增强、类型系统增强、分布式开发范式等更多特性。
下面我们以一个具体的示例来说明eTS的基本组成。如下图所示的代码示例,UI界面会两段文本和一个按钮,当开发者点击按钮时,文本内容会从'Hello World'变为 'Hello ArkUI'。
![ets-get-started](figures/ets-get-started.png)
这个示例中所包含的eTS声明式开发范式的基本组成说明如下:
- 装饰器: 用于装饰类、结构、方法以及变量,赋予其特殊的含义,如上述示例中@Entry、@Component和@State都是装饰器。 具体而言,@Component表示这是个自定义组件;@Entry则表示这是个入口组件;@State表示组件中的状态变量,这个状态变换会引起UI变更。
- 自定义组件:可复用的UI单元,可组合其他组件,如上述被@Component装饰的struct Hello。
- UI描述:声明式的方法来描述UI的结构,例如build()方法中的代码块。
- 内置组件:eTS中默认内置的基本组件和布局组件,开发者可以直接调用,如Column、Text、Divider、Button等。
- 属性方法:用于组件属性的配置,如fontSize()、width()、height()、color()等,可通过链式调用的方式设置多项属性。
- 事件方法:用于添加组件对事件的响应逻辑,统一通过事件方法进行设置,如跟随在Button后面的onClick()。
# 数据懒加载 # 渲染控制
开发框架提供数据懒加载(LazyForEach组件)从提供的数据源中按需迭代数据,并在每次迭代过程中创建相应的组件。LazyForEach定义如下: eTS也提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。
## 条件渲染
```ts 使用if/else进行条件渲染。
LazyForEach(
dataSource: IDataSource, // Data source to be iterated
itemGenerator: (item: any) => void, // child component generator
keyGenerator?: (item: any) => string // (optional) Unique key generator, which is recommended.
): void
interface IDataSource {
totalCount(): number; // Get total count of data
getData(index: number): any; // Get single data by index
registerDataChangeListener(listener: DataChangeListener): void; // Register listener to listening data changes
unregisterDataChangeListener(listener: DataChangeListener): void; // Unregister listener
}
interface DataChangeListener { > **说明:**
onDataReloaded(): void; // Called while data reloaded >
onDataAdd(index: number): void; // Called while single data added > - if条件语句可以使用状态变量。
onDataMove(from: number, to: number): void; // Called while single data moved >
onDataDelete(index: number): void; // Called while single data deleted > - 使用if可以使子组件的渲染依赖条件语句。
onDataChange(index: number): void; // Called while single data changed >
> - 必须在容器组件内使用。
>
> - 某些容器组件限制子组件的类型或数量。将if放置在这些组件内时,这些限制将应用于if和else语句内创建的组件。例如,Grid组件的子组件仅支持GridItem组件,在Grid组件内使用if时,则if条件语句内仅允许使用GridItem组件。
```ts
Column() {
if (this.count < 0) {
Text('count is negative')
} else if (this.count % 2 === 0) {
Divider()
Text('even')
} else {
Divider()
Text('odd')
}
} }
``` ```
## 循环渲染
## 接口 通过循环渲染(ForEach组件)来迭代数组,并为每个数组项创建相应的组件,可减少代码复杂度。
```
ForEach(
arr: any[],
itemGenerator: (item: any, index?: number) => void,
keyGenerator?: (item: any, index?: number) => string
)
```
### LazyForEach **参数:**
LazyForEach(dataSource: IDataSource, itemGenerator: (item: any) =&gt; void, keyGenerator?: (item: any) =&gt; string):void | 参数名 | 参数类型 | 必填 | 参数描述 |
| ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| arr | any[] | 是 | 必须是数组,允许空数组,空数组场景下不会创建子组件。同时允许设置返回值为数组类型的函数,例如arr.slice(1, 3),设置的函数不得改变包括数组本身在内的任何状态变量,如Array.splice、Array.sort或Array.reverse这些改变原数组的函数。 |
| itemGenerator | (item: any, index?: number) => void | 是 | 生成子组件的lambda函数,为给定数组项生成一个或多个子组件,单个组件和子组件列表必须括在大括号“{....}”中。 |
| keyGenerator | (item: any, index?: number) => string | 否 | 匿名参数,用于给定数组项生成唯一且稳定的键值。当子项在数组中的位置更改时,子项的键值不得更改,当数组中的子项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则ForEach中的所有节点都将重建。 |
表1 参数说明 > **说明:**
>
> - ForEach组件必须在容器组件内使用;
>
> - 生成的子组件允许在ForEach的父容器组件中,允许子组件生成器函数中包含if/else条件渲染,同时也允许ForEach包含在if/else条件渲染语句中;
>
> - 子项生成器函数的调用顺序不一定和数组中的数据项相同,在开发过程中不要假设子项生成器和键值生成器函数是否执行以及执行顺序。如下示例可能无法正常工作:
>
> ```
> ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }),
> item => Text(`${item.i}. item.data.label`),
> item => item.data.id.toString())
> ```
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | ## 示例
| ------------- | --------------------------------------- | ---- | ---- | ---------------------------------------- |
| dataSource | IDataSource | 是 | - | 实现IDataSource接口的对象,需要开发者实现相关接口。 |
| itemGenerator | (item:&nbsp;any)&nbsp;=&gt;&nbsp;void | 是 | - | 生成子组件的lambda函数,为给定数组项生成一个或多个子组件,单个组件和子组件列表必须括在大括号“{....}”中。 |
| keyGenerator | (item:&nbsp;any)&nbsp;=&gt;&nbsp;string | 否 | - | 匿名函数,用于键值生成,为给定数组项生成唯一且稳定的键值。当子项在数组中的位置更改时,子项的键值不得更改,当数组中的子项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 |
```ts
// xxx.ets
@Entry
@Component
struct MyComponent {
@State arr: number[] = [10, 20, 30]
表2 IDataSource类型说明 build() {
Column() {
Button() {
Text('Reverse Array')
}.onClick(() => {
this.arr.reverse()
})
| 名称 | 描述 | ForEach(this.arr,
| ---------------------------------------- | ----------- | (item: number) => {
| totalCount():&nbsp;number | 获取数据总数。 | Text(`item value: ${item}`)
| getData(index:&nbsp;number):&nbsp;any | 获取索引对应的数据。 | Divider()
| registerDataChangeListener(listener:DataChangeListener):&nbsp;void | 注册改变数据的控制器。 | },
| unregisterDataChangeListener(listener:DataChangeListener):&nbsp;void | 注销改变数据的控制器。 | (item: number) => item.toString()
)
}
}
}
```
## 数据懒加载
表3 DataChangeListener类型说明 通过数据懒加载(LazyForEach组件)从提供的数据源中按需迭代数据,并在每次迭代过程中创建相应的组件。
| 名称 | 描述 | ```ts
| ---------------------------------------- | ---------------------- | LazyForEach(
| onDataReloaded():&nbsp;void | 重新加载所有数据。 | dataSource: IDataSource,
| onDataAdded(index:&nbsp;number):&nbsp;void <sup>(deprecated) </sup> | 通知组件index的位置有数据添加。 | itemGenerator: (item: any) => void,
| onDataMoved(from:&nbsp;number,&nbsp;to:&nbsp;number):&nbsp;void <sup>(deprecated) </sup> | 通知组件数据从from的位置移到to的位置。 | keyGenerator?: (item: any) => string
| onDataDeleted(index:&nbsp;number):&nbsp;void <sup>(deprecated) </sup> | 通知组件index的位置有数据删除。 | ): void
| onDataChanged(index:&nbsp;number):&nbsp;void <sup>(deprecated) </sup> | 通知组件index的位置有数据变化。 |
| onDataAdd(index:&nbsp;number):&nbsp;void <sup>8+</sup> | 通知组件index的位置有数据添加。 |
| onDataMove(from:&nbsp;number,&nbsp;to:&nbsp;number):&nbsp;void <sup>8+</sup> | 通知组件数据从from的位置移到to的位置。 |
| onDataDelete(index:&nbsp;number):&nbsp;void <sup>8+</sup> | 通知组件index的位置有数据删除。 |
| onDataChange(index:&nbsp;number):&nbsp;void <sup>8+</sup> | 通知组件index的位置有数据变化。 |
interface IDataSource {
totalCount(): number;
getData(index: number): any;
registerDataChangeListener(listener: DataChangeListener): void;
unregisterDataChangeListener(listener: DataChangeListener): void;
}
> **说明:** interface DataChangeListener {
> - 数据懒加载必须在容器组件内使用,且仅有List、Grid以及Swiper组件支持数据的懒加载(即只加载可视部分以及其前后少量数据用于缓冲),其他组件仍然是一次加载所有的数据; onDataReloaded(): void;
> onDataAdd(index: number): void;
> - LazyForEach在每次迭代中,必须且只允许创建一个子组件; onDataMove(from: number, to: number): void;
> onDataDelete(index: number): void;
> - 生成的子组件必须允许在LazyForEach的父容器组件中; onDataChange(index: number): void;
> }
> - 允许LazyForEach包含在if/else条件渲染语句中,不允许LazyForEach中出现if/else条件渲染语句; ```
>
> - 为了高性能渲染,通过DataChangeListener对象的onDataChange方法来更新UI时,仅itemGenerator中的UI描述的组件内使用了状态变量时,才会触发组件刷新; **参数:**
>
> - 子项生成器函数的调用顺序不一定和数据源中的数据项相同,在开发过程中不要假设子项生成器和键值生成器函数是否执行以及执行顺序。如下示例可能无法正常工作: | 参数名 | 参数类型 | 必填 | 参数描述 |
> ```ts | ------------- | --------------------- | ---- | ------------------------------------------------------------ |
> LazyForEach(dataSource, item => {Text(`${++counter}. item.label`)}) | dataSource | IDataSource | 是 | 实现IDataSource接口的对象,需要开发者实现相关接口。 |
> ``` | itemGenerator | (item: any) => void | 是 | 生成子组件的lambda函数,为给定数组项生成一个或多个子组件,单个组件和子组件列表必须括在大括号“{....}”中。 |
> | keyGenerator | (item: any) => string | 否 | 匿名函数,用于键值生成,为给定数组项生成唯一且稳定的键值。当子项在数组中的位置更改时,子项的键值不得更改,当数组中的子项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 |
> 正确的示例如下:
> 表2 IDataSource类型说明
> ```ts
> LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)),
> item => item.data.id.toString())
> ```
| 名称 | 描述 |
| ------------------------------------------------------------ | ---------------------- |
| totalCount(): number | 获取数据总数。 |
| getData(index: number): any | 获取索引对应的数据。 |
| registerDataChangeListener(listener:DataChangeListener): void | 注册改变数据的控制器。 |
| unregisterDataChangeListener(listener:DataChangeListener): void | 注销改变数据的控制器。 |
表3 DataChangeListener类型说明
| 名称 | 描述 |
| -------------------------------------------------------- | -------------------------------------- |
| onDataReloaded(): void | 重新加载所有数据。 |
| onDataAdded(index: number): void (deprecated) | 通知组件index的位置有数据添加。 |
| onDataMoved(from: number, to: number): void (deprecated) | 通知组件数据从from的位置移到to的位置。 |
| onDataDeleted(index: number): void (deprecated) | 通知组件index的位置有数据删除。 |
| onDataChanged(index: number): void (deprecated) | 通知组件index的位置有数据变化。 |
| onDataAdd(index: number): void 8+ | 通知组件index的位置有数据添加。 |
| onDataMove(from: number, to: number): void 8+ | 通知组件数据从from的位置移到to的位置。 |
| onDataDelete(index: number): void 8+ | 通知组件index的位置有数据删除。 |
| onDataChange(index: number): void 8+ | 通知组件index的位置有数据变化。 |
## 示例 ## 示例
```ts ```ts
// Basic implementation of IDataSource to handle data listener
class BasicDataSource implements IDataSource { class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = [] private listeners: DataChangeListener[] = []
...@@ -189,3 +248,23 @@ struct MyComponent { ...@@ -189,3 +248,23 @@ struct MyComponent {
} }
} }
``` ```
> **说明:**
>
> - 数据懒加载必须在容器组件内使用,且仅有List、Grid以及Swiper组件支持数据的懒加载(即只加载可视部分以及其前后少量数据用于缓冲),其他组件仍然是一次加载所有的数据;
>
> - LazyForEach在每次迭代中,必须且只允许创建一个子组件;
>
> - 生成的子组件必须允许在LazyForEach的父容器组件中;
>
> - 允许LazyForEach包含在if/else条件渲染语句中,不允许LazyForEach中出现if/else条件渲染语句;
>
> - 为了高性能渲染,通过DataChangeListener对象的onDataChange方法来更新UI时,仅itemGenerator中的UI描述的组件内使用了状态变量时,才会触发组件刷新;
>
> - 子项生成器函数的调用顺序不一定和数据源中的数据项相同,在开发过程中不要假设子项生成器和键值生成器函数是否执行以及执行顺序。如下示例可能无法正常工作:
>
> ```ts
> LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)),
> item => item.data.id.toString())
> ```
\ No newline at end of file
# 使用限制与扩展
## 在生成器函数中的使用限制
eTS语言的使用在生成器函数中存在一定的限制:
- 表达式仅允许在字符串(${expression})、if条件、ForEach的参数和组件的参数中使用;
- 任何表达式都不能导致任何应用程序状态变量(@State、@Link、@Prop)的改变,否则会导致未定义和潜在不稳定的框架行为;
- 生成器函数内部不能有局部变量。
上述限制都不适用于事件处理函数(例如onClick)的匿函数实现。
## 变量的双向绑定
eTS支持通过$$双向绑定变量,通常应用于状态值频繁改变的变量。
- 当前$$支持基础类型变量,以及@State、@Link和@Prop装饰的变量。
- 当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性的show参数和@State变量之间的渲染,Radio组件的checked属性。
- $$绑定的变量变更时,仅渲染当前组件,提高渲染速度。
```ts
// xxx.ets
@Entry
@Component
struct bindPopup {
@State customPopup: boolean = false
build() {
column() {
button() {
Text('Popup')
}
.onClick(() => {
this.customPopup = !this.customPopup
})
.bindPopup(
$$this.customPopup, {
mesage: "showPopup"
}
)
}
}
}
```
## 状态变量多种数据类型声明使用限制
@State、@Provide、 @Link和@Consume四种状态变量的多种数据类型只能同时由简单数据类型或引用数据类型其中一种构成。
示例:
```ts
// xxx.ets
@Entry
@Component
struct Index {
//错误写法: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(`${ this.message }`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
\ No newline at end of file
# 基本概念
eTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之前,也可以时全局范围内的传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。
![](figures/CoreSpec_figures_state-mgmt-overview.png)
## 页面级变量的状态管理
| 装饰器 | 装饰内容 | 说明 |
| ----------- | ------------------------- | ------------------------------------------------------------ |
| @State | 基本数据类型,类,数组 | 修饰的状态数据被修改时会触发组件的build方法进行UI界面更新。 |
| @Prop | 基本数据类型 | 修改后的状态数据用于在父组件和子组件之间建立单向数据依赖关系。修改父组件关联数据时,更新当前组件的UI。 |
| @Link | 基本数据类型,类,数组 | 父子组件之间的双向数据绑定,父组件的内部状态数据作为数据源,任何一方所做的修改都会反映给另一方。 |
| @Observed | 类 | @Observed应用于类,表示该类中的数据变更被UI页面管理。 |
| @ObjectLink | 被@Observed所装饰类的对象 | 装饰的状态数据被修改时,在父组件或者其他兄弟组件内与它关联的状态数据所在的组件都会更新UI。 |
| @Consume | 基本数据类型,类,数组 | @Consume装饰的变量在感知到@Provide装饰的变量更新后,会触发当前自定义组件的重新渲染。 |
| @Provide | 基本数据类型,类,数组 | @Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。 |
## 应用级变量的状态管理
AppStorage是整个UI应用程序状态的中心“数据库”,UI框架会针对应用程序创建单例AppStorage对象,并提供相应的装饰器和接口供应用程序使用。
- @StorageLink:@StorageLink(name)的原理类似于@Consume(name),不同的是,该给定名称的链接对象是从AppStorage中获得的,在UI组件和AppStorage之间建立双向绑定同步数据。
- @StorageProp:@StorageProp(name)将UI组件属性与AppStorage进行单向同步,AppStorage中值的更改会更新组件中的属性,但UI组件无法更改AppStorage中的属性值。
- AppStorage还提供用于业务逻辑实现的API,用于添加、读取、修改和删除应用程序的状态属性,此API所做的更改会导致修改的状态数据同步到UI组件上进行UI更新。
- PersistentStorage类提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。
- Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态属性,这些属性描述了应用程序运行的设备环境。
...@@ -16,11 +16,11 @@ ...@@ -16,11 +16,11 @@
OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架)。方舟开发框架可为开发者提供应用UI开发所必需的能力,比如多种组件、布局计算、动画能力、UI交互、绘制等。 OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架)。方舟开发框架可为开发者提供应用UI开发所必需的能力,比如多种组件、布局计算、动画能力、UI交互、绘制等。
方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于eTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。以下是两种开发范式的简单对比。 方舟开发框架针对不同目的和技术背景的开发者提供了两种开发范式,分别是基于ArkTS的声明式开发范式(简称“声明式开发范式”)和兼容JS的类Web开发范式(简称“类Web开发范式”)。以下是两种开发范式的简单对比。
| **开发范式名称** | **语言生态** | **UI更新方式** | **适用场景** | **适用人群** | | **开发范式名称** | **语言生态** | **UI更新方式** | **适用场景** | **适用人群** |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| 声明式开发范式 | eTS语言 | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 | | 声明式开发范式 | ArkTS语言 | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 |
| 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的程序应用和卡片 | Web前端开发人员 | | 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的程序应用和卡片 | Web前端开发人员 |
更多UI框架的开发内容及指导,详见[UI开发](../ui/arkui-overview.md) 更多UI框架的开发内容及指导,详见[UI开发](../ui/arkui-overview.md)
...@@ -36,7 +36,7 @@ Ability框架模型结构具有两种形态: ...@@ -36,7 +36,7 @@ Ability框架模型结构具有两种形态:
- **Stage模型**:从API 9开始,Ability框架引入并支持使用Stage模型进行开发。更多Stage模型的内容详见[Stage模型综述](../ability/stage-brief.md) - **Stage模型**:从API 9开始,Ability框架引入并支持使用Stage模型进行开发。更多Stage模型的内容详见[Stage模型综述](../ability/stage-brief.md)
FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持使用eTS语言进行开发。 FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持使用ArkTS语言进行开发。
关于FA模型和Stage模型的整体架构和设计思想等更多区别,详见[Ability框架概述](../ability/ability-brief.md) 关于FA模型和Stage模型的整体架构和设计思想等更多区别,详见[Ability框架概述](../ability/ability-brief.md)
...@@ -49,4 +49,4 @@ FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持 ...@@ -49,4 +49,4 @@ FA模型和Stage模型的工程目录结构存在差异,Stage模型只支持
2. 请参考[配置OpenHarmony SDK](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443),完成**DevEco Studio**的安装和开发环境配置。 2. 请参考[配置OpenHarmony SDK](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443),完成**DevEco Studio**的安装和开发环境配置。
完成上述操作及基本概念的理解后,可参照[使用eTS语言进行开发(Stage模型)](start-with-ets-stage.md)[使用eTS语言开发(FA模型)](start-with-ets-fa.md)[使用JS语言开发(FA模型)](../quick-start/start-with-js-fa.md)中的任一章节进行下一步体验和学习。 完成上述操作及基本概念的理解后,可参照[使用ArkTS语言进行开发(Stage模型)](start-with-ets-stage.md)[使用ArkTS语言开发(FA模型)](start-with-ets-fa.md)[使用JS语言开发(FA模型)](../quick-start/start-with-js-fa.md)中的任一章节进行下一步体验和学习。
# 使用eTS语言开发(FA模型) # 使用ArkTS语言开发(FA模型)
> **说明:** > **说明:**
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
![02](figures/02.png) ![02](figures/02.png)
> **说明:** > **说明:**
> DevEco Studio V3.0 Beta3及更高版本支持使用eTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 > DevEco Studio V3.0 Beta3及更高版本支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。
> >
> 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。
> >
...@@ -288,4 +288,4 @@ ...@@ -288,4 +288,4 @@
![zh-cn_image_0000001363934577](figures/zh-cn_image_0000001363934577.png) ![zh-cn_image_0000001363934577](figures/zh-cn_image_0000001363934577.png)
恭喜您已经使用eTS语言开发(FA模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 恭喜您已经使用ArkTS语言开发(FA模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。
# 使用eTS语言开发(Stage模型) # 使用ArkTS语言开发(Stage模型)
> **说明:** > **说明:**
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
> **说明:** > **说明:**
> >
> 支持使用eTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。 > 支持使用ArkTS[低代码开发](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)方式。
> >
> 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。 > 低代码开发方式具有丰富的UI界面编辑功能,通过可视化界面开发方式快速构建布局,可有效降低开发者的上手成本并提升开发者构建UI界面的效率。
> >
...@@ -287,4 +287,4 @@ ...@@ -287,4 +287,4 @@
![zh-cn_image_0000001311334972](figures/zh-cn_image_0000001311334972.png) ![zh-cn_image_0000001311334972](figures/zh-cn_image_0000001311334972.png)
恭喜您已经使用eTS语言开发(Stage模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。 恭喜您已经使用ArkTS语言开发(Stage模型)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。
...@@ -14,7 +14,7 @@ AbilityContext模块提供允许访问特定Ability的资源的能力,包括 ...@@ -14,7 +14,7 @@ AbilityContext模块提供允许访问特定Ability的资源的能力,包括
在使用AbilityContext的功能前,需要通过Ability子类实例获取。 在使用AbilityContext的功能前,需要通过Ability子类实例获取。
```js ```js
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability';
class MainAbility extends Ability { class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let context = this.context; let context = this.context;
...@@ -34,7 +34,7 @@ class MainAbility extends Ability { ...@@ -34,7 +34,7 @@ class MainAbility extends Ability {
## AbilityContext.startAbility ## AbilityContext.startAbility
startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
启动Ability(callback形式)。 启动Ability(callback形式)。
...@@ -63,7 +63,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void ...@@ -63,7 +63,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
## AbilityContext.startAbility ## AbilityContext.startAbility
startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void;
启动Ability(callback形式)。 启动Ability(callback形式)。
...@@ -1143,7 +1143,7 @@ setMissionLabel(label: string, callback:AsyncCallback&lt;void&gt;): void; ...@@ -1143,7 +1143,7 @@ setMissionLabel(label: string, callback:AsyncCallback&lt;void&gt;): void;
## AbilityContext.setMissionLabel ## AbilityContext.setMissionLabel
setMissionLabel(label: string): Promise&lt;void&gt; setMissionLabel(label: string): Promise&lt;void&gt;;
设置ability在任务中显示的名称(promise形式)。 设置ability在任务中显示的名称(promise形式)。
...@@ -1190,7 +1190,7 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\<void>): void; ...@@ -1190,7 +1190,7 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\<void>): void;
**示例:** **示例:**
```js ```js
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image';
var imagePixelMap; var imagePixelMap;
var color = new ArrayBuffer(0); var color = new ArrayBuffer(0);
var initializationOptions = { var initializationOptions = {
...@@ -1237,7 +1237,7 @@ setMissionIcon(icon: image.PixelMap): Promise\<void>; ...@@ -1237,7 +1237,7 @@ setMissionIcon(icon: image.PixelMap): Promise\<void>;
**示例:** **示例:**
```js ```js
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image';
var imagePixelMap; var imagePixelMap;
var color = new ArrayBuffer(0); var color = new ArrayBuffer(0);
var initializationOptions = { var initializationOptions = {
......
...@@ -472,7 +472,7 @@ promise.then(data => { ...@@ -472,7 +472,7 @@ promise.then(data => {
### PermissionStateChangeType<sup>9+</sup> ### PermissionStateChangeType<sup>9+</sup>
表示权限状态变化操作类型的枚举。 表示权限授权状态变化操作类型的枚举。
**系统接口:** 此接口为系统接口。 **系统接口:** 此接口为系统接口。
...@@ -485,12 +485,14 @@ promise.then(data => { ...@@ -485,12 +485,14 @@ promise.then(data => {
### PermissionStateChangeInfo<sup>9+</sup> ### PermissionStateChangeInfo<sup>9+</sup>
表示某次权限授权状态变化的详情。
**系统接口:** 此接口为系统接口。 **系统接口:** 此接口为系统接口。
**系统能力:** SystemCapability.Security.AccessToken **系统能力:** SystemCapability.Security.AccessToken
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| -------------- | ------------------------- | ---- | ---- | ------------------ | | -------------- | ------------------------- | ---- | ---- | ------------------ |
| change | [PermissionStateChangeType](#permissionstatechangetype9) | 是 | 否 | 权限变化类型 | | change | [PermissionStateChangeType](#permissionstatechangetype9) | 是 | 否 | 权限授权状态变化类型 |
| tokenID | number | 是 | 否 | 调用方的应用身份标识 | | tokenID | number | 是 | 否 | 被订阅的应用身份标识 |
| permissionName | string | 是 | 否 | 状态发生变化的权限名 | | permissionName | string | 是 | 否 | 当前授权状态发生变化的权限名 |
...@@ -227,7 +227,7 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\ ...@@ -227,7 +227,7 @@ publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\
```js ```js
//公共事件相关信息 //公共事件相关信息
var options = { let options = {
code: 0, //公共事件的初始代码 code: 0, //公共事件的初始代码
data: "initial data",//公共事件的初始数据 data: "initial data",//公共事件的初始数据
isOrdered: true //有序公共事件 isOrdered: true //有序公共事件
...@@ -279,7 +279,7 @@ function PublishAsUserCallBack(err) { ...@@ -279,7 +279,7 @@ function PublishAsUserCallBack(err) {
} }
//指定发送的用户 //指定发送的用户
var userId = 100; let userId = 100;
//发布公共事件 //发布公共事件
CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack);
...@@ -311,7 +311,7 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca ...@@ -311,7 +311,7 @@ publishAsUser(event: string, userId: number, options: CommonEventPublishData, ca
```js ```js
//公共事件相关信息 //公共事件相关信息
var options = { let options = {
code: 0, //公共事件的初始代码 code: 0, //公共事件的初始代码
data: "initial data",//公共事件的初始数据 data: "initial data",//公共事件的初始数据
} }
...@@ -326,7 +326,7 @@ function PublishAsUserCallBack(err) { ...@@ -326,7 +326,7 @@ function PublishAsUserCallBack(err) {
} }
//指定发送的用户 //指定发送的用户
var userId = 100; let userId = 100;
//发布公共事件 //发布公共事件
CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack);
...@@ -353,10 +353,10 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac ...@@ -353,10 +353,10 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallbac
```js ```js
var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
//订阅者信息 //订阅者信息
var subscribeInfo = { let subscribeInfo = {
events: ["event"] events: ["event"]
}; };
...@@ -398,10 +398,10 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\<CommonEventS ...@@ -398,10 +398,10 @@ createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\<CommonEventS
**示例:** **示例:**
```js ```js
var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
//订阅者信息 //订阅者信息
var subscribeInfo = { let subscribeInfo = {
events: ["event"] events: ["event"]
}; };
...@@ -434,10 +434,10 @@ subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEven ...@@ -434,10 +434,10 @@ subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEven
**示例:** **示例:**
```js ```js
var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
//订阅者信息 //订阅者信息
var subscribeInfo = { let subscribeInfo = {
events: ["event"] events: ["event"]
}; };
...@@ -486,10 +486,10 @@ unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>): ...@@ -486,10 +486,10 @@ unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>):
**示例:** **示例:**
```js ```js
var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 let subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作
//订阅者信息 //订阅者信息
var subscribeInfo = { let subscribeInfo = {
events: ["event"] events: ["event"]
}; };
...@@ -549,7 +549,7 @@ getCode(callback: AsyncCallback\<number>): void ...@@ -549,7 +549,7 @@ getCode(callback: AsyncCallback\<number>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//获取有序公共事件的结果代码回调 //获取有序公共事件的结果代码回调
function getCodeCallback(err, Code) { function getCodeCallback(err, Code) {
...@@ -579,7 +579,7 @@ getCode(): Promise\<number> ...@@ -579,7 +579,7 @@ getCode(): Promise\<number>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.getCode().then((Code) => { subscriber.getCode().then((Code) => {
console.info("getCode " + JSON.stringify(Code)); console.info("getCode " + JSON.stringify(Code));
...@@ -606,7 +606,7 @@ setCode(code: number, callback: AsyncCallback\<void>): void ...@@ -606,7 +606,7 @@ setCode(code: number, callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//设置有序公共事件的结果代码回调 //设置有序公共事件的结果代码回调
function setCodeCallback(err) { function setCodeCallback(err) {
...@@ -642,7 +642,7 @@ setCode(code: number): Promise\<void> ...@@ -642,7 +642,7 @@ setCode(code: number): Promise\<void>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.setCode(1).then(() => { subscriber.setCode(1).then(() => {
console.info("setCode"); console.info("setCode");
...@@ -668,7 +668,7 @@ getData(callback: AsyncCallback\<string>): void ...@@ -668,7 +668,7 @@ getData(callback: AsyncCallback\<string>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//获取有序公共事件的结果数据回调 //获取有序公共事件的结果数据回调
function getDataCallback(err, Data) { function getDataCallback(err, Data) {
...@@ -698,7 +698,7 @@ getData(): Promise\<string> ...@@ -698,7 +698,7 @@ getData(): Promise\<string>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.getData().then((Data) => { subscriber.getData().then((Data) => {
console.info("getData " + JSON.stringify(Data)); console.info("getData " + JSON.stringify(Data));
...@@ -725,7 +725,7 @@ setData(data: string, callback: AsyncCallback\<void>): void ...@@ -725,7 +725,7 @@ setData(data: string, callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//设置有序公共事件的结果数据回调 //设置有序公共事件的结果数据回调
function setDataCallback(err) { function setDataCallback(err) {
...@@ -761,7 +761,7 @@ setData(data: string): Promise\<void> ...@@ -761,7 +761,7 @@ setData(data: string): Promise\<void>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.setData("publish_data_changed").then(() => { subscriber.setData("publish_data_changed").then(() => {
console.info("setData"); console.info("setData");
...@@ -789,7 +789,7 @@ setCodeAndData(code: number, data: string, callback:AsyncCallback\<void>): void ...@@ -789,7 +789,7 @@ setCodeAndData(code: number, data: string, callback:AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//设置有序公共事件的结果代码和结果数据回调 //设置有序公共事件的结果代码和结果数据回调
function setCodeDataCallback(err) { function setCodeDataCallback(err) {
...@@ -826,7 +826,7 @@ setCodeAndData(code: number, data: string): Promise\<void> ...@@ -826,7 +826,7 @@ setCodeAndData(code: number, data: string): Promise\<void>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.setCodeAndData(1, "publish_data_changed").then(() => { subscriber.setCodeAndData(1, "publish_data_changed").then(() => {
console.info("setCodeAndData"); console.info("setCodeAndData");
...@@ -854,7 +854,7 @@ isOrderedCommonEvent(callback: AsyncCallback\<boolean>): void ...@@ -854,7 +854,7 @@ isOrderedCommonEvent(callback: AsyncCallback\<boolean>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//获取当前公共事件是否为有序事件的回调 //获取当前公共事件是否为有序事件的回调
function isOrderedCallback(err, isOrdered) { function isOrderedCallback(err, isOrdered) {
...@@ -886,7 +886,7 @@ isOrderedCommonEvent(): Promise\<boolean> ...@@ -886,7 +886,7 @@ isOrderedCommonEvent(): Promise\<boolean>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.isOrderedCommonEvent().then((isOrdered) => { subscriber.isOrderedCommonEvent().then((isOrdered) => {
console.info("isOrdered " + JSON.stringify(isOrdered)); console.info("isOrdered " + JSON.stringify(isOrdered));
...@@ -914,7 +914,7 @@ isStickyCommonEvent(callback: AsyncCallback\<boolean>): void ...@@ -914,7 +914,7 @@ isStickyCommonEvent(callback: AsyncCallback\<boolean>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//获取当前公共事件是否为粘性事件的回调 //获取当前公共事件是否为粘性事件的回调
function isStickyCallback(err, isSticky) { function isStickyCallback(err, isSticky) {
...@@ -946,7 +946,7 @@ isStickyCommonEvent(): Promise\<boolean> ...@@ -946,7 +946,7 @@ isStickyCommonEvent(): Promise\<boolean>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.isStickyCommonEvent().then((isSticky) => { subscriber.isStickyCommonEvent().then((isSticky) => {
console.info("isSticky " + JSON.stringify(isSticky)); console.info("isSticky " + JSON.stringify(isSticky));
...@@ -972,7 +972,7 @@ abortCommonEvent(callback: AsyncCallback\<void>): void ...@@ -972,7 +972,7 @@ abortCommonEvent(callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//取消当前有序公共事件的回调 //取消当前有序公共事件的回调
function abortCallback(err) { function abortCallback(err) {
...@@ -1002,7 +1002,7 @@ abortCommonEvent(): Promise\<void> ...@@ -1002,7 +1002,7 @@ abortCommonEvent(): Promise\<void>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.abortCommonEvent().then(() => { subscriber.abortCommonEvent().then(() => {
console.info("abortCommonEvent"); console.info("abortCommonEvent");
...@@ -1028,7 +1028,7 @@ clearAbortCommonEvent(callback: AsyncCallback\<void>): void ...@@ -1028,7 +1028,7 @@ clearAbortCommonEvent(callback: AsyncCallback\<void>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//清除当前公共事件取消状态的回调 //清除当前公共事件取消状态的回调
function clearAbortCallback(err) { function clearAbortCallback(err) {
...@@ -1058,7 +1058,7 @@ clearAbortCommonEvent(): Promise\<void> ...@@ -1058,7 +1058,7 @@ clearAbortCommonEvent(): Promise\<void>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.clearAbortCommonEvent().then(() => { subscriber.clearAbortCommonEvent().then(() => {
console.info("clearAbortCommonEvent"); console.info("clearAbortCommonEvent");
...@@ -1084,7 +1084,7 @@ getAbortCommonEvent(callback: AsyncCallback\<boolean>): void ...@@ -1084,7 +1084,7 @@ getAbortCommonEvent(callback: AsyncCallback\<boolean>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//获取当前有序公共事件是否取消的回调 //获取当前有序公共事件是否取消的回调
function getAbortCallback(err, AbortCommonEvent) { function getAbortCallback(err, AbortCommonEvent) {
...@@ -1114,7 +1114,7 @@ getAbortCommonEvent(): Promise\<boolean> ...@@ -1114,7 +1114,7 @@ getAbortCommonEvent(): Promise\<boolean>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { subscriber.getAbortCommonEvent().then((AbortCommonEvent) => {
console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent));
...@@ -1140,7 +1140,7 @@ getSubscribeInfo(callback: AsyncCallback\<CommonEventSubscribeInfo>): void ...@@ -1140,7 +1140,7 @@ getSubscribeInfo(callback: AsyncCallback\<CommonEventSubscribeInfo>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//获取订阅者信息回调 //获取订阅者信息回调
function getSubscribeInfoCallback(err, SubscribeInfo) { function getSubscribeInfoCallback(err, SubscribeInfo) {
...@@ -1170,7 +1170,7 @@ getSubscribeInfo(): Promise\<CommonEventSubscribeInfo> ...@@ -1170,7 +1170,7 @@ getSubscribeInfo(): Promise\<CommonEventSubscribeInfo>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.getSubscribeInfo().then((SubscribeInfo) => { subscriber.getSubscribeInfo().then((SubscribeInfo) => {
console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo));
...@@ -1196,7 +1196,7 @@ finishCommonEvent(callback: AsyncCallback\<void\>): void ...@@ -1196,7 +1196,7 @@ finishCommonEvent(callback: AsyncCallback\<void\>): void
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
//结束当前有序公共事件的回调 //结束当前有序公共事件的回调
function finishCommonEventCallback(err) { function finishCommonEventCallback(err) {
...@@ -1226,7 +1226,7 @@ finishCommonEvent(): Promise\<void\> ...@@ -1226,7 +1226,7 @@ finishCommonEvent(): Promise\<void\>
**示例:** **示例:**
```js ```js
var subscriber; //创建成功的订阅者对象 let subscriber; //创建成功的订阅者对象
subscriber.finishCommonEvent().then(() => { subscriber.finishCommonEvent().then(() => {
console.info("FinishCommonEvent"); console.info("FinishCommonEvent");
......
...@@ -26,10 +26,10 @@ on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata) ...@@ -26,10 +26,10 @@ on(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdata)
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ------------------------ | | -------- | ----------------------------------- | ---- | --------------------------------------- |
| event | [InnerEvent](#innerevent) | 是 | 持续订阅的事件 | | event | [InnerEvent](#innerevent) | 是 | 持续订阅的事件,其中EventPriority不生效 |
| callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 | | callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 |
**示例:** **示例:**
...@@ -53,10 +53,10 @@ once(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdat ...@@ -53,10 +53,10 @@ once(event: [InnerEvent](#innerevent), callback: Callback\<[EventData](#eventdat
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ------------------------ | | -------- | ----------------------------------- | ---- | --------------------------------------- |
| event | [InnerEvent](#innerevent) | 是 | 单次订阅的事件 | | event | [InnerEvent](#innerevent) | 是 | 单次订阅的事件,其中EventPriority不生效 |
| callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 | | callback | Callback\<[EventData](#eventdata)\> | 是 | 接收订阅事件时的回调处理 |
**示例:** **示例:**
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册