提交 78926e1a 编写于 作者: Y yeyinglong 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into listalign

Signed-off-by: Nyeyinglong <yeyinglong@live.com>
...@@ -210,6 +210,7 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease ...@@ -210,6 +210,7 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-display.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-display.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-effectKit.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang
......
# Ability Call Development # Ability Call Development
## When to Use ## When to Use
Ability call is an extension of the ability capabilities. It enables an ability to be invoked by external systems. In this way, the ability can be displayed as a UI page on the foreground and created and run on the background. You can use the **Call** APIs to implement data sharing between different abilities through inter-process communication (IPC). There are two roles in the ability call: caller and callee. The following scenarios are involved in the ability call development: Ability call is an extension of the ability capability. It enables an ability to be invoked by and communicate with external systems. The ability invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two abilities (caller ability and callee ability) through inter-process communication (IPC).
- Creating a callee
- Accessing the callee
The following figure shows the ability call process. The core API used for the ability call is `startAbilityByCall`, which differs from `startAbility` in the following ways:
- `startAbilityByCall` supports ability startup in the foreground and background, whereas `startAbility` supports ability startup in the foreground only.
- The caller ability can use the `Caller` object returned by `startAbilityByCall` to communicate with the callee ability, but `startAbility` does not provide the communication capability.
Ability call is usually used in the following scenarios:
- Communicating with the callee ability
- Starting the callee ability in the background
**Table 1** Terms used in the ability call
|Term|Description|
|:------|:------|
|Caller ability|Ability that triggers the ability call.|
|Callee ability|Ability invoked by the ability call.|
|Caller |Object returned by `startAbilityByCall` and used by the caller ability to communicate with the callee ability.|
|Callee |Object held by the callee ability to communicate with the caller ability.|
|IPC |Inter-process communication.|
The ability call process is as follows:
- The caller ability uses `startAbilityByCall` to obtain a `Caller` object and uses `call()` of the `Caller` object to send data to the callee ability.
- The callee ability, which holds a `Callee` object, uses `on()` of the `Callee` object to register a callback. This callback is invoked when the callee ability receives data from the caller ability.
![stage-call](figures/stage-call.png) ![stage-call](figures/stage-call.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**<br/>
> The startup mode of the callee must be **singleton**. > The launch type of the callee ability must be `singleton`.
> Currently, only system applications and Service Extension abilities can use the **Call** APIs to access the callee. > Currently, only system applications can use the ability call.
## Available APIs ## Available APIs
The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller). The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller).
**Table 1** Ability call APIs **Table 2** Ability call APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|startAbilityByCall(want: Want): Promise\<Caller>|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| |startAbilityByCall(want: Want): Promise\<Caller>|Starts an ability in the foreground (through the `want` configuration) or background (default) and obtains the `Caller` object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md#serviceextensioncontextstartabilitybycall).|
|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee registers a method.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.|
|off(method: string): void|Callback invoked when the callee deregisters a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.|
|call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee.| |call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee ability.|
|callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| |callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.|
|release(): void|Releases the caller interface.| |release(): void|Releases the `Caller` object.|
|onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.| |onRelease(callback: OnReleaseCallBack): void|Callback invoked when the `Caller` object is released.|
## How to Develop ## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> The procedure for developing the ability call is as follows:
> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. 1. Create a callee ability.
### Creating a Callee 2. Access the callee ability.
For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener. > **NOTE**
1. Configure the ability startup mode. >
> The code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently.
### Creating a Callee Ability
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use `on()` to register a listener. When data does not need to be received, use `off()` to deregister the listener.
**1. Configure the ability launch type.**
Set the ability of the callee to **singleton** in the **module.json5** file. Set `launchType` of the callee ability to `singleton` in the `module.json5` file.
|JSON Field|Description| |JSON Field|Description|
|:------|:------| |:------|:------|
|"launchType"|Ability startup mode. Set this parameter to **singleton**.| |"launchType"|Ability launch type. Set this parameter to `singleton`.|
An example of the ability configuration is as follows: An example of the ability configuration is as follows:
```json ```json
...@@ -51,13 +71,13 @@ An example of the ability configuration is as follows: ...@@ -51,13 +71,13 @@ An example of the ability configuration is as follows:
"visible": true "visible": true
}] }]
``` ```
2. Import the **Ability** module. **2. Import the Ability module.**
``` ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
``` ```
3. Define the agreed sequenceable data. **3. Define the agreed sequenceable data.**
The data formats sent and received by the caller and callee must be consistent. In the following example, the data consists of numbers and strings. The sample code snippet is as follows: The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The code snippet is as follows:
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0
...@@ -81,23 +101,23 @@ export default class MySequenceable { ...@@ -81,23 +101,23 @@ export default class MySequenceable {
} }
} }
``` ```
4. Implement **Callee.on** and **Callee.off**. **4. Implement `Callee.on` and `Callee.off`.**
The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the `MSG_SEND_METHOD` listener is registered in `onCreate` of the ability and deregistered in `onDestroy`. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The code snippet is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]' const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
function sendMsgCallback(data) { function sendMsgCallback(data) {
Logger.log(TAG, 'CalleeSortFunc called') console.log('CalleeSortFunc called')
// Obtain the sequenceable data sent by the caller. // Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '') let receivedData = new MySequenceable(0, '')
data.readSequenceable(receivedData) data.readSequenceable(receivedData)
Logger.log(TAG, `receiveData[${receivedData.num}, ${receivedData.str}]`) console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// Process the data. // Process the data.
// Return the sequenceable data result to the caller. // Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`)
} }
...@@ -106,7 +126,7 @@ export default class CalleeAbility extends Ability { ...@@ -106,7 +126,7 @@ export default class CalleeAbility extends Ability {
try { try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback) this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} catch (error) { } catch (error) {
Logger.error(TAG, `${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
} }
} }
...@@ -120,15 +140,27 @@ export default class CalleeAbility extends Ability { ...@@ -120,15 +140,27 @@ export default class CalleeAbility extends Ability {
} }
``` ```
### Accessing the Callee ### Accessing the Callee Ability
1. Import the **Ability** module. **1. Import the Ability module.**
``` ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
``` ```
2. Obtain the caller interface. **2. Obtain the `Caller` object.**
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller interface of the ability. The following example uses **this.context** to obtain the **context** attribute of the **Ability** instance, uses **startAbilityByCall** to start the callee, obtain the caller interface, and register the **onRelease** listener of the caller. You need to implement processing based on service requirements. The sample code snippet is as follows: The `context` attribute of the ability implements `startAbilityByCall` to obtain the `Caller` object for communication. The following example uses `this.context` to obtain the `context` attribute of the ability, uses `startAbilityByCall` to start the callee ability, obtain the `Caller` object, and register the `onRelease` listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows:
```ts ```ts
// Register the onRelease listener of the caller ability.
private regOnRelease(caller) {
try {
caller.onRelease((msg) => {
console.log(`caller onRelease is called ${msg}`)
})
console.log('caller register OnRelease succeed')
} catch (error) {
console.log(`caller register OnRelease failed with ${error}`)
}
}
async onButtonGetCaller() { async onButtonGetCaller() {
try { try {
this.caller = await context.startAbilityByCall({ this.caller = await context.startAbilityByCall({
...@@ -136,73 +168,74 @@ async onButtonGetCaller() { ...@@ -136,73 +168,74 @@ async onButtonGetCaller() {
abilityName: 'CalleeAbility' abilityName: 'CalleeAbility'
}) })
if (this.caller === undefined) { if (this.caller === undefined) {
Logger.error(TAG, 'get caller failed') console.log('get caller failed')
return return
} }
Logger.log(TAG, 'get caller success') console.log('get caller success')
this.regOnRelease(this.caller) this.regOnRelease(this.caller)
} catch (error) { } catch (error) {
Logger.error(TAG, `get caller failed with ${error}`) console.log(`get caller failed with ${error}`)
} }
}.catch((error) => { }
console.error(TAG + 'get caller failed with ' + error)
})
``` ```
In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: In the cross-device scenario, you need to specify the ID of the peer device. The code snippet is as follows:
```ts ```ts
let TAG = '[MainAbility] ' async onButtonGetRemoteCaller() {
var caller = undefined var caller = undefined
let context = this.context var context = this.context
context.startAbilityByCall({ context.startAbilityByCall({
deviceId: getRemoteDeviceId(), deviceId: getRemoteDeviceId(),
bundleName: 'com.samples.CallApplication', bundleName: 'com.samples.CallApplication',
abilityName: 'CalleeAbility' abilityName: 'CalleeAbility'
}).then((data) => { }).then((data) => {
if (data != null) { if (data != null) {
caller = data caller = data
console.log(TAG + 'get remote caller success') console.log('get remote caller success')
// Register the onRelease listener of the caller. // Register the onRelease listener of the caller ability.
caller.onRelease((msg) => { caller.onRelease((msg) => {
console.log(TAG + 'remote caller onRelease is called ' + msg) console.log(`remote caller onRelease is called ${msg}`)
}) })
console.log(TAG + 'remote caller register OnRelease succeed') console.log('remote caller register OnRelease succeed')
} }
}).catch((error) => { }).catch((error) => {
console.error(TAG + 'get remote caller failed with ' + error) console.error(`get remote caller failed with ${error}`)
}) })
}
``` ```
Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: Obtain the ID of the peer device from `DeviceManager`. Note that the `getTrustedDeviceListSync` API is open only to system applications. The code snippet is as follows:
```ts ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass; var dmClass;
function getRemoteDeviceId() { function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) { if (typeof dmClass === 'object' && dmClass != null) {
var list = dmClass.getTrustedDeviceListSync(); var list = dmClass.getTrustedDeviceListSync()
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null")
return; return
} }
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId)
return list[0].deviceId; return list[0].deviceId
} else { } else {
console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null")
} }
} }
``` ```
In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows:
```ts ```ts
let context = this.context requestPermission() {
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'] let context = this.context
context.requestPermissionsFromUser(permissions).then((data) => { let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) console.log("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => { }).catch((error) => {
console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) console.log("Failed to request permission from user with error: "+ JSON.stringify(error))
}) })
}
``` ```
3. Send agreed sequenceable data. **3. Send agreed sequenceable data.**
The sequenceable data can be sent to the callee with or without a return value. The method and sequenceable data must be consistent with those of the callee. The following example describes how to invoke the **Call** API to send data to the callee. The sample code snippet is as follows: The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. The code snippet is as follows:
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
async onButtonCall() { async onButtonCall() {
...@@ -210,12 +243,12 @@ async onButtonCall() { ...@@ -210,12 +243,12 @@ async onButtonCall() {
let msg = new MySequenceable(1, 'origin_Msg') let msg = new MySequenceable(1, 'origin_Msg')
await this.caller.call(MSG_SEND_METHOD, msg) await this.caller.call(MSG_SEND_METHOD, msg)
} catch (error) { } catch (error) {
Logger.error(TAG, `caller call failed with ${error}`) console.log(`caller call failed with ${error}`)
} }
} }
``` ```
In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: In the following, `CallWithResult` is used to send data `originMsg` to the callee ability and assign the data processed by the `CallSendMsg` method to `backMsg`. The code snippet is as follows:
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = '' originMsg: string = ''
...@@ -224,26 +257,28 @@ async onButtonCallWithResult(originMsg, backMsg) { ...@@ -224,26 +257,28 @@ async onButtonCallWithResult(originMsg, backMsg) {
try { try {
let msg = new MySequenceable(1, originMsg) let msg = new MySequenceable(1, originMsg)
const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg) const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg)
Logger.log(TAG, 'caller callWithResult succeed') console.log('caller callWithResult succeed')
let result = new MySequenceable(0, '') let result = new MySequenceable(0, '')
data.readSequenceable(result) data.readSequenceable(result)
backMsg(result.str) backMsg(result.str)
Logger.log(TAG, `caller result is [${result.num}, ${result.str}]`) console.log(`caller result is [${result.num}, ${result.str}]`)
} catch (error) { } catch (error) {
Logger.error(TAG, `caller callWithResult failed with ${error}`) console.log(`caller callWithResult failed with ${error}`)
} }
} }
``` ```
4. Release the caller interface. **4. Release the `Caller` object.**
When the caller interface is no longer required, call the **release** API to release it. The sample code snippet is as follows: When the `Caller` object is no longer required, use `release()` to release it. The code snippet is as follows:
```ts ```ts
try { releaseCall() {
try {
this.caller.release() this.caller.release()
this.caller = undefined this.caller = undefined
Logger.log(TAG, 'caller release succeed') console.log('caller release succeed')
} catch (error) { } catch (error) {
Logger.error(TAG, `caller release failed with ${error}`) console.log(`caller release failed with ${error}`)
}
} }
``` ```
...@@ -285,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ ...@@ -285,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ
1. Connect the development board running the OpenHarmony standard system to the computer. 1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signaure**. Wait until the automatic signing is complete, and click **OK**. See the following figure. 2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png) ![06](figures/06.png)
......
...@@ -127,7 +127,7 @@ Starts an ability. This API uses a promise to return the result. ...@@ -127,7 +127,7 @@ Starts an ability. This API uses a promise to return the result.
windowMode: 0, windowMode: 0,
}; };
this.context.startAbility(want, options) this.context.startAbility(want, options)
.then((data) => { .then(() => {
console.log('Operation successful.') console.log('Operation successful.')
}).catch((error) => { }).catch((error) => {
console.log('Operation failed.'); console.log('Operation failed.');
...@@ -407,8 +407,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re ...@@ -407,8 +407,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
this.context.startServiceExtensionAbility(want) this.context.startServiceExtensionAbility(want)
.then((data) => { .then(() => {
console.log('---------- startServiceExtensionAbility success, data: -----------', data); console.log('---------- startServiceExtensionAbility success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- startServiceExtensionAbility fail, err: -----------', err); console.log('---------- startServiceExtensionAbility fail, err: -----------', err);
...@@ -477,8 +477,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ...@@ -477,8 +477,8 @@ Starts a new Service Extension ability with the account ID specified. This API u
}; };
var accountId = 100; var accountId = 100;
this.context.startServiceExtensionAbilityWithAccount(want,accountId) this.context.startServiceExtensionAbilityWithAccount(want,accountId)
.then((data) => { .then(() => {
console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); console.log('---------- startServiceExtensionAbilityWithAccount success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err);
...@@ -539,8 +539,8 @@ Stops a Service Extension ability in the same application. This API uses a promi ...@@ -539,8 +539,8 @@ Stops a Service Extension ability in the same application. This API uses a promi
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
this.context.stopServiceExtensionAbility(want) this.context.stopServiceExtensionAbility(want)
.then((data) => { .then(() => {
console.log('---------- stopServiceExtensionAbility success, data: -----------', data); console.log('---------- stopServiceExtensionAbility success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); console.log('---------- stopServiceExtensionAbility fail, err: -----------', err);
...@@ -610,8 +610,8 @@ Stops a Service Extension ability in the same application with the account ID sp ...@@ -610,8 +610,8 @@ Stops a Service Extension ability in the same application with the account ID sp
}; };
var accountId = 100; var accountId = 100;
this.context.stopServiceExtensionAbilityWithAccount(want,accountId) this.context.stopServiceExtensionAbilityWithAccount(want,accountId)
.then((data) => { .then(() => {
console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); console.log('---------- stopServiceExtensionAbilityWithAccount success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err);
...@@ -658,8 +658,8 @@ Terminates this ability. This API uses a promise to return the result. ...@@ -658,8 +658,8 @@ Terminates this ability. This API uses a promise to return the result.
**Example** **Example**
```js ```js
this.context.terminateSelf().then((data) => { this.context.terminateSelf().then(() => {
console.log('success:' + JSON.stringify(data)); console.log('success');
}).catch((error) => { }).catch((error) => {
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
}); });
...@@ -851,8 +851,8 @@ Disconnects a connection. This API uses a promise to return the result. ...@@ -851,8 +851,8 @@ Disconnects a connection. This API uses a promise to return the result.
```js ```js
var connectionNumber = 0; var connectionNumber = 0;
this.context.disconnectAbility(connectionNumber).then((data) => { this.context.disconnectAbility(connectionNumber).then(() => {
console.log('disconnectAbility success, data: ', data); console.log('disconnectAbility success');
}).catch((err) => { }).catch((err) => {
console.log('disconnectAbility fail, err: ', err); console.log('disconnectAbility fail, err: ', err);
}); });
...@@ -888,7 +888,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r ...@@ -888,7 +888,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r
startAbilityByCall(want: Want): Promise&lt;Caller&gt;; startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
Starts an ability in the foreground or background and obtains the caller interface for communication with the ability. Starts an ability in the foreground or background and obtains the caller object for communicating with the ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -909,7 +909,7 @@ Starts an ability in the foreground or background and obtains the caller interfa ...@@ -909,7 +909,7 @@ Starts an ability in the foreground or background and obtains the caller interfa
```js ```js
let caller = undefined; let caller = undefined;
// Start an ability in the background without passing parameters. // Start an ability in the background by not passing parameters.
var wantBackground = { var wantBackground = {
bundleName: "com.example.myservice", bundleName: "com.example.myservice",
moduleName: "entry", moduleName: "entry",
...@@ -1050,8 +1050,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu ...@@ -1050,8 +1050,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu
windowMode: 0, windowMode: 0,
}; };
this.context.startAbilityWithAccount(want, accountId, options) this.context.startAbilityWithAccount(want, accountId, options)
.then((data) => { .then(() => {
console.log('---------- startAbilityWithAccount success, data: -----------', data); console.log('---------- startAbilityWithAccount success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err); console.log('---------- startAbilityWithAccount fail, err: -----------', err);
...@@ -1164,8 +1164,8 @@ Sets a label for this ability in the mission. This API uses a promise to return ...@@ -1164,8 +1164,8 @@ Sets a label for this ability in the mission. This API uses a promise to return
**Example** **Example**
```js ```js
this.context.setMissionLabel("test").then((data) => { this.context.setMissionLabel("test").then(() => {
console.log('success:' + JSON.stringify(data)); console.log('success');
}).catch((error) => { }).catch((error) => {
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
}); });
...@@ -1254,8 +1254,8 @@ Sets an icon for this ability in the mission. This API uses a promise to return ...@@ -1254,8 +1254,8 @@ Sets an icon for this ability in the mission. This API uses a promise to return
console.log('--------- createPixelMap fail, err: ---------', err) console.log('--------- createPixelMap fail, err: ---------', err)
}); });
this.context.setMissionIcon(imagePixelMap) this.context.setMissionIcon(imagePixelMap)
.then((data) => { .then(() => {
console.log('-------------- setMissionIcon success, data: -------------', data); console.log('-------------- setMissionIcon success -------------');
}) })
.catch((err) => { .catch((err) => {
console.log('-------------- setMissionIcon fail, err: -------------', err); console.log('-------------- setMissionIcon fail, err: -------------', err);
......
...@@ -32,7 +32,7 @@ Enumerates the action constants of the **Want** object. ...@@ -32,7 +32,7 @@ Enumerates the action constants of the **Want** object.
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | | ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | | ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. |
| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. | | ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. |
| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. | | ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for opening a contact or picture. |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | Action of launching the UI for photographing. | | ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | Action of launching the UI for photographing. |
| ACTION_VIDEO_CAPTURE<sup>8+</sup> | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | | ACTION_VIDEO_CAPTURE<sup>8+</sup> | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. |
| ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. | | ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. |
......
...@@ -49,6 +49,7 @@ import Want from '@ohos.application.Want'; ...@@ -49,6 +49,7 @@ import Want from '@ohos.application.Want';
- Passing a file descriptor (FD) - Passing a file descriptor (FD)
``` js ``` js
import fileio from '@ohos.fileio';
var fd; var fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
...@@ -59,7 +60,7 @@ import Want from '@ohos.application.Want'; ...@@ -59,7 +60,7 @@ import Want from '@ohos.application.Want';
"deviceId": "", // An empty deviceId indicates the local device. "deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test", "bundleName": "com.extreme.test",
"abilityName": "MainAbility", "abilityName": "MainAbility",
"moduleName": "entry" // moduleName is optional. "moduleName": "entry", // moduleName is optional.
"parameters": { "parameters": {
"keyFd":{"type":"FD", "value":fd} "keyFd":{"type":"FD", "value":fd}
} }
......
...@@ -4911,7 +4911,7 @@ audioCapturer.getBufferSize().then((data) => { ...@@ -4911,7 +4911,7 @@ audioCapturer.getBufferSize().then((data) => {
console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
bufferSize = data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.error(`AudioFrameworkRecLog: getBufferSize: EROOR: ${err}`); console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`);
}); });
audioCapturer.read(bufferSize, true, async(err, buffer) => { audioCapturer.read(bufferSize, true, async(err, buffer) => {
if (!err) { if (!err) {
......
...@@ -2810,10 +2810,11 @@ This is a system API. ...@@ -2810,10 +2810,11 @@ This is a system API.
| Name | Value | Description | | Name | Value | Description |
| -------------------- | ---- | ------------ | | -------------------- | ---- | ------------ |
| DEVICE_EARPIECE | 0 | Headset device. | | DEVICE_EARPIECE | 0 | Earpiece. |
| DEVICE_SPEAKER | 1 | Speaker device.| | DEVICE_SPEAKER | 1 | Speaker.|
| DEVICE_WIRED_HEADSET | 2 | Wired headset device.| | DEVICE_WIRED_HEADSET | 2 | Wired headset.|
| DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. | | DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. |
| DEVICE_MIC | 4 | Microphone. |
## CallRestrictionType<sup>8+</sup> ## CallRestrictionType<sup>8+</sup>
......
...@@ -631,7 +631,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the resu ...@@ -631,7 +631,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the resu
**Example** **Example**
```js ```js
cameraManager.createPreviewOutput(profile, survaceId).then((previewoutput) => { cameraManager.createPreviewOutput(profile, surfaceId).then((previewoutput) => {
console.log('Promise returned with previewOutput created.'); console.log('Promise returned with previewOutput created.');
}) })
``` ```
...@@ -2262,7 +2262,7 @@ cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(er ...@@ -2262,7 +2262,7 @@ cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(er
console.log(`Failed to check exposure mode supported ${err.message}`); console.log(`Failed to check exposure mode supported ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of isExposureModeSupported'); console.log('Callback returned with the successful execution of isExposureModeSupported');
}) })
``` ```
...@@ -2365,7 +2365,7 @@ cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { ...@@ -2365,7 +2365,7 @@ cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => {
console.log(`Failed to set the exposure mode ${err.message}`); console.log(`Failed to set the exposure mode ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setExposureMode'); console.log('Callback returned with the successful execution of setExposureMode');
}) })
``` ```
...@@ -2464,7 +2464,7 @@ cameraInput.setMeteringPoint(Point1,(err) => { ...@@ -2464,7 +2464,7 @@ cameraInput.setMeteringPoint(Point1,(err) => {
console.log(`Failed to set the exposure point ${err.message}`); console.log(`Failed to set the exposure point ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setMeteringPoint'); console.log('Callback returned with the successful execution of setMeteringPoint');
}) })
``` ```
...@@ -2571,7 +2571,7 @@ cameraInput.setExposureBias(-4,(err) => { ...@@ -2571,7 +2571,7 @@ cameraInput.setExposureBias(-4,(err) => {
console.log(`Failed to set the exposure bias ${err.message}`); console.log(`Failed to set the exposure bias ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setExposureBias'); console.log('Callback returned with the successful execution of setExposureBias');
}) })
``` ```
...@@ -3545,7 +3545,7 @@ previewOutput.stop((err) => { ...@@ -3545,7 +3545,7 @@ previewOutput.stop((err) => {
console.error(`Failed to stop the previewOutput. ${err.message}`); console.error(`Failed to stop the previewOutput. ${err.message}`);
return; return;
} }
console.log('Callback returned with previewOutput stoped.'); console.log('Callback returned with previewOutput stopped.');
}) })
``` ```
...@@ -3567,7 +3567,7 @@ Stops outputting preview streams. This API uses a promise to return the result. ...@@ -3567,7 +3567,7 @@ Stops outputting preview streams. This API uses a promise to return the result.
```js ```js
previewOutput.stop().then(() => { previewOutput.stop().then(() => {
console.log('Callback returned with previewOutput stoped.'); console.log('Callback returned with previewOutput stopped.');
}) })
``` ```
...@@ -4476,7 +4476,7 @@ metadataOutput.stop((err) => { ...@@ -4476,7 +4476,7 @@ metadataOutput.stop((err) => {
console.error(`Failed to stop the metadataOutput. ${err.message}`); console.error(`Failed to stop the metadataOutput. ${err.message}`);
return; return;
} }
console.log('Callback returned with metadataOutput stoped.'); console.log('Callback returned with metadataOutput stopped.');
}) })
``` ```
...@@ -4498,7 +4498,7 @@ Stops outputting metadata. This API uses a promise to return the result. ...@@ -4498,7 +4498,7 @@ Stops outputting metadata. This API uses a promise to return the result.
```js ```js
metadataOutput.stop().then(() => { metadataOutput.stop().then(() => {
console.log('Callback returned with metadataOutput stoped.'); console.log('Callback returned with metadataOutput stopped.');
}) })
``` ```
......
...@@ -33,8 +33,7 @@ var observer = { ...@@ -33,8 +33,7 @@ var observer = {
console.log('onUnhandledException, errorMsg: ', errorMsg) console.log('onUnhandledException, errorMsg: ', errorMsg)
} }
} }
const registerErrorObserverNumber=errorManager.registerErrorObserver(observer) errorManager.registerErrorObserver(observer)
console.info(registerErrorObserverNumber)
``` ```
## ErrorManager.unregisterErrorObserver ## ErrorManager.unregisterErrorObserver
...@@ -123,11 +122,4 @@ var observer = { ...@@ -123,11 +122,4 @@ var observer = {
} }
} }
errorManager.registerErrorObserver(observer) errorManager.registerErrorObserver(observer)
.then((data) => {
console.log('----------- registerErrorObserver success ----------', data);
})
.catch((err) => {
console.log('----------- registerErrorObserver fail ----------', err);
})
``` ```
...@@ -105,7 +105,7 @@ Enumerates the widget parameters. ...@@ -105,7 +105,7 @@ Enumerates the widget parameters.
| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. |
| ABILITY_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.ability_name" | Ability name. | | ABILITY_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.ability_name" | Ability name. |
| DEVICE_ID_KEY<sup>9+</sup> | "ohos.extra.param.key.device_id" | Device ID.<br>This is a system API. | | DEVICE_ID_KEY<sup>9+</sup> | "ohos.extra.param.key.device_id" | Device ID.<br>This is a system API. |
| BUNDLE_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.<br>This is a system API. | | BUNDLE_NAME_KEY<sup>9+</sup> | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.|
## FormDimension ## FormDimension
......
...@@ -89,7 +89,7 @@ Writes event information to the event file. This API uses a promise to return th ...@@ -89,7 +89,7 @@ Writes event information to the event file. This API uses a promise to return th
| Name | Type | Mandatory| Description| | Name | Type | Mandatory| Description|
| --------- | ----------------------- | ---- | --------------- | | --------- | ----------------------- | ---- | --------------- |
| eventType | [EventType](#eventtype) | Yes | Application event type.| | info | [SysEventInfo](#syseventinfo) | Yes | System event information.|
**Return value** **Return value**
......
# Internationalization – I18N # Internationalization – I18N
This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402.
The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities.
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md).
## Modules to Import ## Modules to Import
......
...@@ -92,7 +92,7 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i ...@@ -92,7 +92,7 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i
readPixelsToBuffer(dst: ArrayBuffer): Promise\<void> readPixelsToBuffer(dst: ArrayBuffer): Promise\<void>
Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. Reads data of this pixel map and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. If this pixel map is created in the BGRA_8888 format, the data read is the same as the original data.
**System capability**: SystemCapability.Multimedia.Image.Core **System capability**: SystemCapability.Multimedia.Image.Core
...@@ -123,7 +123,7 @@ pixelmap.readPixelsToBuffer(readBuffer).then(() => { ...@@ -123,7 +123,7 @@ pixelmap.readPixelsToBuffer(readBuffer).then(() => {
readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\<void>): void readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\<void>): void
Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. Reads data of this pixel map and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. If this pixel map is created in the BGRA_8888 format, the data read is the same as the original data.
**System capability**: SystemCapability.Multimedia.Image.Core **System capability**: SystemCapability.Multimedia.Image.Core
...@@ -810,7 +810,7 @@ Crops this image based on the input size. This API uses an asynchronous callback ...@@ -810,7 +810,7 @@ Crops this image based on the input size. This API uses an asynchronous callback
```js ```js
async function () { async function () {
await pixelMap.crop(3x3); await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
} }
``` ```
...@@ -838,7 +838,7 @@ Crops this image based on the input size. This API uses a promise to return the ...@@ -838,7 +838,7 @@ Crops this image based on the input size. This API uses a promise to return the
```js ```js
async function () { async function () {
await pixelMap.crop(3x3); await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
} }
``` ```
...@@ -910,7 +910,7 @@ Creates an **ImageSource** instance based on the URI. ...@@ -910,7 +910,7 @@ Creates an **ImageSource** instance based on the URI.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------------- | | ------ | ------ | ---- | ---------------------------------- |
| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.| | uri | string | Yes | Image path. Currently, only the application sandbox path is supported.<br>Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.|
**Return value** **Return value**
...@@ -937,7 +937,7 @@ Creates an **ImageSource** instance based on the URI. ...@@ -937,7 +937,7 @@ Creates an **ImageSource** instance based on the URI.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | ----------------------------------- | | ------- | ------------------------------- | ---- | ----------------------------------- |
| uri | string | Yes | Image path. Currently, only the application sandbox path is supported. | | uri | string | Yes | Image path. Currently, only the application sandbox path is supported.<br>Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.|
| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.| | options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
**Return value** **Return value**
...@@ -2166,7 +2166,7 @@ Enumerates the scale modes of images. ...@@ -2166,7 +2166,7 @@ Enumerates the scale modes of images.
| Name | Default Value| Description | | Name | Default Value| Description |
| --------------- | ------ | -------------------------------------------------- | | --------------- | ------ | -------------------------------------------------- |
| CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.| | CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.|
| FIT_TARGET_SIZE | 2 | Reduces the image size to the dimensions of the target. | | FIT_TARGET_SIZE | 0 | Reduces the image size to the dimensions of the target. |
## SourceOptions<sup>9+</sup> ## SourceOptions<sup>9+</sup>
...@@ -2231,7 +2231,7 @@ Defines the option for image packing. ...@@ -2231,7 +2231,7 @@ Defines the option for image packing.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | --------------------------------------------------- | | ------- | ------ | ---- | ---- | --------------------------------------------------- |
| format | string | Yes | Yes | Format of the packed image. | | format | string | Yes | Yes | Format of the packed image.<br>Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp. |
| quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.|
## GetImagePropertyOptions<sup>7+</sup> ## GetImagePropertyOptions<sup>7+</sup>
......
# Internationalization – Intl # Internationalization – Intl
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402.
> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The [I18N](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
> **NOTE**
> >
> - This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402. For details about the enhanced I18N capabilities, see [I18N](js-apis-i18n.md). > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
......
...@@ -724,15 +724,17 @@ Disconnects this ability from the Service ability. This API uses a promise to re ...@@ -724,15 +724,17 @@ Disconnects this ability from the Service ability. This API uses a promise to re
startAbilityByCall(want: Want): Promise&lt;Caller&gt;; startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
Starts an ability in the background and obtains the caller interface for communication. Starts an ability in the foreground or background and obtains the caller object for communicating with the ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, including the ability name, module name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.|
**Return value** **Return value**
...@@ -744,16 +746,38 @@ Starts an ability in the background and obtains the caller interface for communi ...@@ -744,16 +746,38 @@ Starts an ability in the background and obtains the caller interface for communi
```js ```js
let caller = undefined; let caller = undefined;
this.context.startAbilityByCall({
// Start an ability in the background by not passing parameters.
var wantBackground = {
bundleName: "com.example.myservice", bundleName: "com.example.myservice",
moduleName: "entry", moduleName: "entry",
abilityName: "MainAbility", abilityName: "MainAbility",
deviceId: "" deviceId: ""
}).then((obj) => { };
this.context.startAbilityByCall(wantBackground)
.then((obj) => {
caller = obj;
console.log('GetCaller Success');
}).catch((error) => {
console.log(`GetCaller failed with ${error}`);
});
// Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true.
var wantForeground = {
bundleName: "com.example.myservice",
moduleName: "entry",
abilityName: "MainAbility",
deviceId: "",
parameters: {
"ohos.aafwk.param.callAbilityToForeground": true
}
};
this.context.startAbilityByCall(wantForeground)
.then((obj) => {
caller = obj; caller = obj;
console.log('Caller GetCaller Get ' + caller); console.log('GetCaller success');
}).catch((e) => { }).catch((error) => {
console.log('Caller GetCaller error ' + e); console.log(`GetCaller failed with ${error}`);
}); });
``` ```
...@@ -71,7 +71,7 @@ let promise = sms.createMessage(pdu, specification); ...@@ -71,7 +71,7 @@ let promise = sms.createMessage(pdu, specification);
promise.then(data => { promise.then(data => {
console.log(`createMessage success, promise: data->${JSON.stringify(data)}`); console.log(`createMessage success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`createMessage fail, promise: err->${JSON.stringify(err)}`); console.error(`createMessage failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -154,7 +154,7 @@ let promise = sms.getDefaultSmsSlotId(); ...@@ -154,7 +154,7 @@ let promise = sms.getDefaultSmsSlotId();
promise.then(data => { promise.then(data => {
console.log(`getDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`); console.log(`getDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`getDefaultSmsSlotId fail, promise: err->${JSON.stringify(err)}`); console.error(`getDefaultSmsSlotId failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -164,7 +164,7 @@ setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback&lt;void&gt;\): void ...@@ -164,7 +164,7 @@ setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback&lt;void&gt;\): void
Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.SET_TELEPHONY_STATE **Required permission**: ohos.permission.SET_TELEPHONY_STATE
...@@ -192,7 +192,7 @@ setDefaultSmsSlotId\(slotId: number\): Promise&lt;void&gt; ...@@ -192,7 +192,7 @@ setDefaultSmsSlotId\(slotId: number\): Promise&lt;void&gt;
Sets the default slot of the SIM card used to send SMS messages. This API uses a promise to return the result. Sets the default slot of the SIM card used to send SMS messages. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.SET_TELEPHONY_STATE **Required permission**: ohos.permission.SET_TELEPHONY_STATE
...@@ -217,7 +217,7 @@ let promise = sms.setDefaultSmsSlotId(0); ...@@ -217,7 +217,7 @@ let promise = sms.setDefaultSmsSlotId(0);
promise.then(data => { promise.then(data => {
console.log(`setDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`); console.log(`setDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`setDefaultSmsSlotId fail, promise: err->${JSON.stringify(err)}`); console.error(`setDefaultSmsSlotId failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -227,7 +227,7 @@ setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback<void\>\): ...@@ -227,7 +227,7 @@ setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback<void\>\):
Sets the short message service center (SMSC) address. This API uses an asynchronous callback to return the result. Sets the short message service center (SMSC) address. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) **Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission)
...@@ -258,7 +258,7 @@ setSmscAddr\(slotId: number, smscAddr: string\): Promise\<void\> ...@@ -258,7 +258,7 @@ setSmscAddr\(slotId: number, smscAddr: string\): Promise\<void\>
Sets the SMSC address. This API uses a promise to return the result. Sets the SMSC address. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) **Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission)
...@@ -286,7 +286,7 @@ let promise = sms.setSmscAddr(slotId, smscAddr); ...@@ -286,7 +286,7 @@ let promise = sms.setSmscAddr(slotId, smscAddr);
promise.then(data => { promise.then(data => {
console.log(`setSmscAddr success, promise: data->${JSON.stringify(data)}`); console.log(`setSmscAddr success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`setSmscAddr fail, promise: err->${JSON.stringify(err)}`); console.error(`setSmscAddr failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -297,7 +297,7 @@ getSmscAddr\(slotId: number, callback: AsyncCallback<string\>\): void ...@@ -297,7 +297,7 @@ getSmscAddr\(slotId: number, callback: AsyncCallback<string\>\): void
Obtains the SMSC address. This API uses an asynchronous callback to return the result. Obtains the SMSC address. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) **Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission)
...@@ -326,7 +326,7 @@ getSmscAddr\(slotId: number\): Promise<string\> ...@@ -326,7 +326,7 @@ getSmscAddr\(slotId: number\): Promise<string\>
Obtains the SMSC address. This API uses a promise to return the result. Obtains the SMSC address. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) **Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission)
...@@ -352,7 +352,7 @@ let promise = sms.getSmscAddr(slotId); ...@@ -352,7 +352,7 @@ let promise = sms.getSmscAddr(slotId);
promise.then(data => { promise.then(data => {
console.log(`getSmscAddr success, promise: data->${JSON.stringify(data)}`); console.log(`getSmscAddr success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`getSmscAddr fail, promise: err->${JSON.stringify(err)}`); console.error(`getSmscAddr failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -381,7 +381,7 @@ splitMessage(content: string, callback: AsyncCallback<Array<string\>>): void ...@@ -381,7 +381,7 @@ splitMessage(content: string, callback: AsyncCallback<Array<string\>>): void
Splits an SMS message into multiple segments. This API uses an asynchronous callback to return the result. Splits an SMS message into multiple segments. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.SEND_MESSAGES
...@@ -410,7 +410,7 @@ splitMessage(content: string): Promise<Array<string\>> ...@@ -410,7 +410,7 @@ splitMessage(content: string): Promise<Array<string\>>
Splits an SMS message into multiple segments. This API uses a promise to return the result. Splits an SMS message into multiple segments. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.SEND_MESSAGES
...@@ -436,7 +436,7 @@ let promise = sms.splitMessage(content); ...@@ -436,7 +436,7 @@ 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)}`);
}).catch(err => { }).catch(err => {
console.error(`splitMessage fail, promise: err->${JSON.stringify(err)}`); console.error(`splitMessage failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -446,7 +446,7 @@ addSimMessage(options: SimMessageOptions, callback: AsyncCallback<void\>): void ...@@ -446,7 +446,7 @@ addSimMessage(options: SimMessageOptions, callback: AsyncCallback<void\>): void
Adds a SIM message. This API uses an asynchronous callback to return the result. Adds a SIM message. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES
...@@ -480,7 +480,7 @@ addSimMessage(options: SimMessageOptions): Promise<void\> ...@@ -480,7 +480,7 @@ addSimMessage(options: SimMessageOptions): Promise<void\>
Adds a SIM message. This API uses a promise to return the result. Adds a SIM message. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES
...@@ -511,7 +511,7 @@ let promise = sms.addSimMessage(simMessageOptions); ...@@ -511,7 +511,7 @@ let promise = sms.addSimMessage(simMessageOptions);
promise.then(data => { promise.then(data => {
console.log(`addSimMessage success, promise: data->${JSON.stringify(data)}`); console.log(`addSimMessage success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`addSimMessage fail, promise: err->${JSON.stringify(err)}`); console.error(`addSimMessage failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -521,7 +521,7 @@ delSimMessage(slotId: number, msgIndex: number, callback: AsyncCallback<void\>): ...@@ -521,7 +521,7 @@ delSimMessage(slotId: number, msgIndex: number, callback: AsyncCallback<void\>):
Deletes a SIM message. This API uses an asynchronous callback to return the result. Deletes a SIM message. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES
...@@ -552,7 +552,7 @@ delSimMessage(slotId: number, msgIndex: number): Promise<void\> ...@@ -552,7 +552,7 @@ delSimMessage(slotId: number, msgIndex: number): Promise<void\>
Deletes a SIM message. This API uses a promise to return the result. Deletes a SIM message. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES
...@@ -580,7 +580,7 @@ let promise = sms.delSimMessage(slotId, msgIndex); ...@@ -580,7 +580,7 @@ let promise = sms.delSimMessage(slotId, msgIndex);
promise.then(data => { promise.then(data => {
console.log(`delSimMessage success, promise: data->${JSON.stringify(data)}`); console.log(`delSimMessage success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`delSimMessage fail, promise: err->${JSON.stringify(err)}`); console.error(`delSimMessage failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -590,7 +590,7 @@ updateSimMessage(options: UpdateSimMessageOptions, callback: AsyncCallback<void\ ...@@ -590,7 +590,7 @@ updateSimMessage(options: UpdateSimMessageOptions, callback: AsyncCallback<void\
Updates a SIM message. This API uses an asynchronous callback to return the result. Updates a SIM message. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES
...@@ -625,7 +625,7 @@ updateSimMessage(options: UpdateSimMessageOptions): Promise<void\> ...@@ -625,7 +625,7 @@ updateSimMessage(options: UpdateSimMessageOptions): Promise<void\>
Updates a SIM message. This API uses a promise to return the result. Updates a SIM message. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES
...@@ -657,7 +657,7 @@ let promise = sms.updateSimMessage(updateSimMessageOptions); ...@@ -657,7 +657,7 @@ let promise = sms.updateSimMessage(updateSimMessageOptions);
promise.then(data => { promise.then(data => {
console.log(`updateSimMessage success, promise: data->${JSON.stringify(data)}`); console.log(`updateSimMessage success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`updateSimMessage fail, promise: err->${JSON.stringify(err)}`); console.error(`updateSimMessage failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -667,7 +667,7 @@ getAllSimMessages(slotId: number, callback: AsyncCallback<Array<SimShortMessage\ ...@@ -667,7 +667,7 @@ getAllSimMessages(slotId: number, callback: AsyncCallback<Array<SimShortMessage\
Obtains all SIM card messages. This API uses an asynchronous callback to return the result. Obtains all SIM card messages. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS **Required permission**: ohos.permission.RECEIVE_SMS
...@@ -696,7 +696,7 @@ getAllSimMessages(slotId: number): Promise<Array<SimShortMessage\>> ...@@ -696,7 +696,7 @@ getAllSimMessages(slotId: number): Promise<Array<SimShortMessage\>>
Obtains all SIM card messages. This API uses a promise to return the result. Obtains all SIM card messages. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS **Required permission**: ohos.permission.RECEIVE_SMS
...@@ -722,7 +722,7 @@ let promise = sms.getAllSimMessages(slotId); ...@@ -722,7 +722,7 @@ let promise = sms.getAllSimMessages(slotId);
promise.then(data => { promise.then(data => {
console.log(`getAllSimMessages success, promise: data->${JSON.stringify(data)}`); console.log(`getAllSimMessages success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`getAllSimMessages fail, promise: err->${JSON.stringify(err)}`); console.error(`getAllSimMessages failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -732,7 +732,7 @@ setCBConfig(options: CBConfigOptions, callback: AsyncCallback<void\>): void ...@@ -732,7 +732,7 @@ setCBConfig(options: CBConfigOptions, callback: AsyncCallback<void\>): void
Sets the cell broadcast configuration. This API uses an asynchronous callback to return the result. Sets the cell broadcast configuration. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS **Required permission**: ohos.permission.RECEIVE_SMS
...@@ -766,7 +766,7 @@ setCBConfig(options: CBConfigOptions): Promise<void\> ...@@ -766,7 +766,7 @@ setCBConfig(options: CBConfigOptions): Promise<void\>
Sets the cell broadcast configuration. This API uses a promise to return the result. Sets the cell broadcast configuration. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**Required permission**: ohos.permission.RECEIVE_SMS **Required permission**: ohos.permission.RECEIVE_SMS
...@@ -797,7 +797,7 @@ let promise = sms.setCBConfig(cbConfigOptions); ...@@ -797,7 +797,7 @@ 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 fail, promise: err->${JSON.stringify(err)}`); console.error(`setCBConfig failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -807,7 +807,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean, callback ...@@ -807,7 +807,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean, callback
Obtains SMS message segment information. This API uses an asynchronous callback to return the result. Obtains SMS message segment information. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -836,7 +836,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean): Promise ...@@ -836,7 +836,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean): Promise
Obtains SMS message segment information. This API uses a promise to return the result. Obtains SMS message segment information. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -862,7 +862,7 @@ let promise = sms.getSmsSegmentsInfo(slotId, "message", false); ...@@ -862,7 +862,7 @@ 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 fail, promise: err->${JSON.stringify(err)}`); console.error(`getSmsSegmentsInfo failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -872,7 +872,7 @@ isImsSmsSupported(callback: AsyncCallback<boolean\>): void ...@@ -872,7 +872,7 @@ isImsSmsSupported(callback: AsyncCallback<boolean\>): void
Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result. Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -897,7 +897,7 @@ isImsSmsSupported(): Promise<boolean\> ...@@ -897,7 +897,7 @@ isImsSmsSupported(): Promise<boolean\>
Checks whether SMS is supported on IMS. This API uses a promise to return the result. Checks whether SMS is supported on IMS. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -914,7 +914,7 @@ let promise = sms.isImsSmsSupported(); ...@@ -914,7 +914,7 @@ let promise = sms.isImsSmsSupported();
promise.then(data => { promise.then(data => {
console.log(`isImsSmsSupported success, promise: data->${JSON.stringify(data)}`); console.log(`isImsSmsSupported success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`isImsSmsSupported fail, promise: err->${JSON.stringify(err)}`); console.error(`isImsSmsSupported failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -924,7 +924,7 @@ getImsShortMessageFormat(callback: AsyncCallback<string\>): void ...@@ -924,7 +924,7 @@ getImsShortMessageFormat(callback: AsyncCallback<string\>): void
Obtains the SMS format supported by the IMS. This API uses an asynchronous callback to return the result. Obtains the SMS format supported by the IMS. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -949,7 +949,7 @@ getImsShortMessageFormat(): Promise<string\> ...@@ -949,7 +949,7 @@ getImsShortMessageFormat(): Promise<string\>
Obtains the SMS format supported by the IMS. This API uses a promise to return the result. Obtains the SMS format supported by the IMS. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -966,7 +966,7 @@ let promise = sms.getImsShortMessageFormat(); ...@@ -966,7 +966,7 @@ let promise = sms.getImsShortMessageFormat();
promise.then(data => { promise.then(data => {
console.log(`getImsShortMessageFormat success, promise: data->${JSON.stringify(data)}`); console.log(`getImsShortMessageFormat success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`getImsShortMessageFormat fail, promise: err->${JSON.stringify(err)}`); console.error(`getImsShortMessageFormat failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -976,7 +976,7 @@ decodeMms(mmsFilePathName: string | Array<number\>, callback: AsyncCallback<MmsI ...@@ -976,7 +976,7 @@ decodeMms(mmsFilePathName: string | Array<number\>, callback: AsyncCallback<MmsI
Decodes MMS messages. This API uses an asynchronous callback to return the result. Decodes MMS messages. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1003,7 +1003,7 @@ decodeMms(mmsFilePathName: string | Array<number\>): Promise<MmsInformation\> ...@@ -1003,7 +1003,7 @@ decodeMms(mmsFilePathName: string | Array<number\>): Promise<MmsInformation\>
Decodes MMS messages. This API uses a promise to return the result. Decodes MMS messages. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1027,7 +1027,7 @@ let promise = sms.getSmscAddr(mmsFilePathName); ...@@ -1027,7 +1027,7 @@ let promise = sms.getSmscAddr(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 => {
console.error(`decodeMms fail, promise: err->${JSON.stringify(err)}`); console.error(`decodeMms failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -1037,7 +1037,7 @@ encodeMms(mms: MmsInformation, callback: AsyncCallback<Array<number\>>): void ...@@ -1037,7 +1037,7 @@ encodeMms(mms: MmsInformation, callback: AsyncCallback<Array<number\>>): void
Encodes MMS messages. This API uses an asynchronous callback to return the result. Encodes MMS messages. This API uses an asynchronous callback to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1072,7 +1072,7 @@ encodeMms(mms: MmsInformation): Promise<Array<number\>> ...@@ -1072,7 +1072,7 @@ encodeMms(mms: MmsInformation): Promise<Array<number\>>
Encodes MMS messages. This API uses a promise to return the result. Encodes MMS messages. This API uses a promise to return the result.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1104,7 +1104,7 @@ let promise = sms.encodeMms(mmsInformation); ...@@ -1104,7 +1104,7 @@ let promise = sms.encodeMms(mmsInformation);
promise.then(data => { promise.then(data => {
console.log(`encodeMms success, promise: data->${JSON.stringify(data)}`); console.log(`encodeMms success, promise: data->${JSON.stringify(data)}`);
}).catch(err => { }).catch(err => {
console.error(`encodeMms fail, promise: err->${JSON.stringify(err)}`); console.error(`encodeMms failed, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
...@@ -1203,7 +1203,7 @@ Enumerates SMS message sending results. ...@@ -1203,7 +1203,7 @@ Enumerates SMS message sending results.
Defines the MMS message information. Defines the MMS message information.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1217,7 +1217,7 @@ This is a system API. ...@@ -1217,7 +1217,7 @@ This is a system API.
Defines an MMS message sending request. Defines an MMS message sending request.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1243,7 +1243,7 @@ This is a system API. ...@@ -1243,7 +1243,7 @@ This is a system API.
Defines the MMS message sending configuration. Defines the MMS message sending configuration.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1258,7 +1258,7 @@ This is a system API. ...@@ -1258,7 +1258,7 @@ This is a system API.
Defines an MMS notification index. Defines an MMS notification index.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1279,7 +1279,7 @@ This is a system API. ...@@ -1279,7 +1279,7 @@ This is a system API.
Defines an MMS confirmation index. Defines an MMS confirmation index.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1293,7 +1293,7 @@ This is a system API. ...@@ -1293,7 +1293,7 @@ This is a system API.
Defines the MMS message retrieval configuration. Defines the MMS message retrieval configuration.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1318,7 +1318,7 @@ This is a system API. ...@@ -1318,7 +1318,7 @@ This is a system API.
Defines the original MMS message reading index. Defines the original MMS message reading index.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1336,7 +1336,7 @@ This is a system API. ...@@ -1336,7 +1336,7 @@ This is a system API.
Defines the MMS message reading index. Defines the MMS message reading index.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1354,7 +1354,7 @@ This is a system API. ...@@ -1354,7 +1354,7 @@ This is a system API.
Defines the attachment of an MMS message. Defines the attachment of an MMS message.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1375,7 +1375,7 @@ This is a system API. ...@@ -1375,7 +1375,7 @@ This is a system API.
Defines an MMSC address. Defines an MMSC address.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1388,7 +1388,7 @@ This is a system API. ...@@ -1388,7 +1388,7 @@ This is a system API.
Enumerates message types. Enumerates message types.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1408,7 +1408,7 @@ This is a system API. ...@@ -1408,7 +1408,7 @@ This is a system API.
Enumerates MMS message priorities. Enumerates MMS message priorities.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1422,7 +1422,7 @@ This is a system API. ...@@ -1422,7 +1422,7 @@ This is a system API.
Enumerates MMS versions. Enumerates MMS versions.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1437,7 +1437,7 @@ This is a system API. ...@@ -1437,7 +1437,7 @@ This is a system API.
Enumerates MMS character sets. Enumerates MMS character sets.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1462,7 +1462,7 @@ This is a system API. ...@@ -1462,7 +1462,7 @@ This is a system API.
Enumerates disposition types. Enumerates disposition types.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1476,7 +1476,7 @@ This is a system API. ...@@ -1476,7 +1476,7 @@ This is a system API.
Enumerates report types. Enumerates report types.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1489,7 +1489,7 @@ This is a system API. ...@@ -1489,7 +1489,7 @@ This is a system API.
Defines the cell broadcast configuration options. Defines the cell broadcast configuration options.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1505,7 +1505,7 @@ This is a system API. ...@@ -1505,7 +1505,7 @@ This is a system API.
Defines the SIM message status. Defines the SIM message status.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1521,7 +1521,7 @@ This is a system API. ...@@ -1521,7 +1521,7 @@ This is a system API.
Enumerates RAN types. Enumerates RAN types.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1534,7 +1534,7 @@ This is a system API. ...@@ -1534,7 +1534,7 @@ This is a system API.
Enumerates SMS encoding schemes. Enumerates SMS encoding schemes.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1549,7 +1549,7 @@ This is a system API. ...@@ -1549,7 +1549,7 @@ This is a system API.
Defines the SIM message options. Defines the SIM message options.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1564,7 +1564,7 @@ This is a system API. ...@@ -1564,7 +1564,7 @@ This is a system API.
Defines the updating SIM message options. Defines the updating SIM message options.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1580,7 +1580,7 @@ This is a system API. ...@@ -1580,7 +1580,7 @@ This is a system API.
Defines a SIM message. Defines a SIM message.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1594,7 +1594,7 @@ This is a system API. ...@@ -1594,7 +1594,7 @@ This is a system API.
Defines an MMS message delivery index. Defines an MMS message delivery index.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1610,7 +1610,7 @@ This is a system API. ...@@ -1610,7 +1610,7 @@ This is a system API.
Defines an MMS response index. Defines an MMS response index.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
...@@ -1625,7 +1625,7 @@ This is a system API. ...@@ -1625,7 +1625,7 @@ This is a system API.
Defines the SMS message segment information. Defines the SMS message segment information.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
......
...@@ -123,7 +123,7 @@ In this example, declare the permission under the **acls** field: ...@@ -123,7 +123,7 @@ In this example, declare the permission under the **acls** field:
"allowed-acls": [ "allowed-acls": [
"ohos.permission.PERMISSION2" "ohos.permission.PERMISSION2"
] ]
}, }
} }
``` ```
......
...@@ -265,7 +265,7 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -265,7 +265,7 @@ import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.wantAgent';
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
function startBackgroundRunning() { function startContinuousTask() {
let wantAgentInfo = { let wantAgentInfo = {
// List of operations to be executed after the notification is clicked. // List of operations to be executed after the notification is clicked.
wants: [ wants: [
...@@ -293,7 +293,7 @@ function startBackgroundRunning() { ...@@ -293,7 +293,7 @@ function startBackgroundRunning() {
}); });
} }
function stopBackgroundRunning() { function stopContinuousTask() {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded"); console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => { }).catch((err) => {
...@@ -301,6 +301,13 @@ function stopBackgroundRunning() { ...@@ -301,6 +301,13 @@ function stopBackgroundRunning() {
}); });
} }
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
let mMyStub; let mMyStub;
class MyStub extends rpc.RemoteObject { class MyStub extends rpc.RemoteObject {
...@@ -315,11 +322,11 @@ class MyStub extends rpc.RemoteObject { ...@@ -315,11 +322,11 @@ class MyStub extends rpc.RemoteObject {
console.log('ServiceAbility onRemoteRequest called'); console.log('ServiceAbility onRemoteRequest called');
// The meaning of code is user-defined. // The meaning of code is user-defined.
if (code === 1) { if (code === 1) {
// Received the request code for requesting a continuous task. // Receive the request code for requesting a continuous task.
startContinuousTask(); startContinuousTask();
// Execute the continuous task. // Execute the continuous task.
} else if (code === 2) { } else if (code === 2) {
// Received the request code for canceling the continuous task. // Receive the request code for canceling the continuous task.
stopContinuousTask(); stopContinuousTask();
} else { } else {
console.log('ServiceAbility unknown request code'); console.log('ServiceAbility unknown request code');
...@@ -332,9 +339,9 @@ export default { ...@@ -332,9 +339,9 @@ export default {
onStart(want) { onStart(want) {
console.info('ServiceAbility onStart'); console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test"); mMyStub = new MyStub("ServiceAbility-test");
startBackgroundRunning(); // Call the API to start the task.
// Execute a specific continuous task in the background. startContinuousTask();
stopBackgroundRunning(); processAsyncJobs();
}, },
onStop() { onStop() {
console.info('ServiceAbility onStop'); console.info('ServiceAbility onStop');
......
...@@ -53,7 +53,7 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -53,7 +53,7 @@ You can create a subwindow, such as a dialog box, and set its properties.
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
var windowClass = null; let windowClass = null;
// 1. Method 1: Create a subwindow. // 1. Method 1: Create a subwindow.
window.create("subWindow", window.WindowType.TYPE_APP, (err, data) => { window.create("subWindow", window.WindowType.TYPE_APP, (err, data) => {
if (err.code) { if (err.code) {
...@@ -87,7 +87,6 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -87,7 +87,6 @@ You can create a subwindow, such as a dialog box, and set its properties.
After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness. After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness.
```js ```js
// 2. Move the subwindow. // 2. Move the subwindow.
windowClass.moveTo(300, 300, (err, data) => { windowClass.moveTo(300, 300, (err, data) => {
...@@ -111,7 +110,6 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -111,7 +110,6 @@ You can create a subwindow, such as a dialog box, and set its properties.
Call `loadContent` and `show` to load and display the content in the subwindow. Call `loadContent` and `show` to load and display the content in the subwindow.
```js ```js
// 3. Load the page content to the subwindow. // 3. Load the page content to the subwindow.
windowClass.loadContent("pages/page2", (err, data) => { windowClass.loadContent("pages/page2", (err, data) => {
...@@ -135,7 +133,6 @@ You can create a subwindow, such as a dialog box, and set its properties. ...@@ -135,7 +133,6 @@ You can create a subwindow, such as a dialog box, and set its properties.
When the subwindow is no longer needed, you can call `destroy` to destroy it. When the subwindow is no longer needed, you can call `destroy` to destroy it.
```js ```js
// 4. Destroy the subwindow when a click event outside the window is detected. // 4. Destroy the subwindow when a click event outside the window is detected.
windowClass.on('touchOutside', () => { windowClass.on('touchOutside', () => {
...@@ -160,13 +157,16 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -160,13 +157,16 @@ To create a better video watching and gaming experience, you can use the immersi
1. Obtain the main window. 1. Obtain the main window.
The immersive window feature can be implemented only after the main window is obtained. You can call `window.getTopWindow` to obtain the main window. > **NOTE**
>
> The immersive window feature can be implemented only after the main window is obtained.
>
> Ensure that the top window of the application is the main window. You can use `window.getTopWindow` to obtain the main window.
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
var mainWindowClass = null; let mainWindowClass = null;
// 1. Obtain the main window. // 1. Obtain the main window.
window.getTopWindow((err, data) => { window.getTopWindow((err, data) => {
if (err.code) { if (err.code) {
...@@ -186,7 +186,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -186,7 +186,7 @@ To create a better video watching and gaming experience, you can use the immersi
```js ```js
// 2. Use method 1 to implement the immersive effect. // 2. Use method 1 to implement the immersive effect.
var isFullScreen = true; let isFullScreen = true;
mainWindowClass.setFullScreen(isFullScreen, (err, data) => { mainWindowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
...@@ -195,7 +195,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -195,7 +195,7 @@ To create a better video watching and gaming experience, you can use the immersi
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
}); });
// 2. Use method 2 to implement the immersive effect. // 2. Use method 2 to implement the immersive effect.
var names = []; let names = [];
mainWindowClass.setSystemBarEnable(names, (err, data) => { mainWindowClass.setSystemBarEnable(names, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
...@@ -204,7 +204,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -204,7 +204,7 @@ To create a better video watching and gaming experience, you can use the immersi
console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data));
}); });
// 2. Use method 3 to implement the immersive effect. // 2. Use method 3 to implement the immersive effect.
var isLayoutFullScreen = true; let isLayoutFullScreen = true;
mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
...@@ -212,7 +212,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -212,7 +212,7 @@ To create a better video watching and gaming experience, you can use the immersi
} }
console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data));
}); });
var SystemBarProperties = { let sysBarProps = {
statusBarColor: '#ff00ff', statusBarColor: '#ff00ff',
navigationBarColor: '#00ff00', navigationBarColor: '#00ff00',
// The following properties are supported since API version 7. // The following properties are supported since API version 7.
...@@ -222,7 +222,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -222,7 +222,7 @@ To create a better video watching and gaming experience, you can use the immersi
statusBarContentColor: '#ffffff', statusBarContentColor: '#ffffff',
navigationBarContentColor: '#ffffff' navigationBarContentColor: '#ffffff'
}; };
mainWindowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { mainWindowClass.setSystemBarProperties(sysBarProps, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err));
return; return;
...@@ -235,7 +235,6 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -235,7 +235,6 @@ To create a better video watching and gaming experience, you can use the immersi
Call `loadContent` and `show` to load and display the content in the immersive window. Call `loadContent` and `show` to load and display the content in the immersive window.
```js ```js
// 3. Load the page content to the immersive window. // 3. Load the page content to the immersive window.
mainWindowClass.loadContent("pages/page3", (err, data) => { mainWindowClass.loadContent("pages/page3", (err, data) => {
......
...@@ -56,25 +56,21 @@ In the stage model, the main window of an application is created and maintained ...@@ -56,25 +56,21 @@ In the stage model, the main window of an application is created and maintained
### How to Develop ### How to Develop
1. Obtain the main window. 1. Obtain the main window.
Call `getMainWindow` to obtain the main window of the application. Call `getMainWindow` to obtain the main window of the application.
2. Set the properties of the main window. 2. Set the properties of the main window.
You can set multiple properties of the main window, such as the background color, brightness, and whether the main window is touchable. The code snippet below uses the `touchable` property as an example. You can set multiple properties of the main window, such as the background color, brightness, and whether the main window is touchable. The code snippet below uses the `touchable` property as an example.
3. Load content for the main window. 3. Load content for the main window.
Call `loadContent` to load the page content to the main window. Call `loadContent` to load the page content to the main window.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
class MainAbility extends Ability { class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// 1. Obtain the main window of the application. // 1. Obtain the main window of the application.
var windowClass = null; let windowClass = null;
windowStage.getMainWindow((err, data) => { windowStage.getMainWindow((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
...@@ -83,7 +79,7 @@ class MainAbility extends Ability { ...@@ -83,7 +79,7 @@ class MainAbility extends Ability {
windowClass = data; windowClass = data;
console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
// 2. Set the touchable property of the main window. // 2. Set the touchable property of the main window.
var isTouchable = true; let isTouchable = true;
windowClass.setTouchable(isTouchable, (err, data) => { windowClass.setTouchable(isTouchable, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err));
...@@ -113,31 +109,26 @@ You can create an application subwindow, such as a dialog box, and set its prope ...@@ -113,31 +109,26 @@ You can create an application subwindow, such as a dialog box, and set its prope
### How to Develop ### How to Develop
1. Create or obtain a subwindow. 1. Create or obtain a subwindow.
Call `createSubWindow` to create a subwindow. Call `createSubWindow` to create a subwindow.
Call `getSubWindow` to obtain a subwindow. Call `getSubWindow` to obtain a subwindow.
2. Set the properties of the subwindow. 2. Set the properties of the subwindow.
After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness. After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness.
3. Load content for the subwindow and show it. 3. Load content for the subwindow and show it.
Call `loadContent` and `show` to load and display the content in the subwindow. Call `loadContent` and `show` to load and display the content in the subwindow.
4. Destroy the subwindow. 4. Destroy the subwindow.
When the subwindow is no longer needed, you can call `destroy` to destroy it. When the subwindow is no longer needed, you can call `destroy` to destroy it.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
class MainAbility extends Ability { class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// 1. Create a subwindow. // 1. Create a subwindow.
var sub_windowClass = null; let sub_windowClass = null;
windowStage.createSubWindow("mySubWindow", (err, data) => { windowStage.createSubWindow("mySubWindow", (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err));
...@@ -210,7 +201,6 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -210,7 +201,6 @@ To create a better video watching and gaming experience, you can use the immersi
### How to Develop ### How to Develop
1. Obtain the main window. 1. Obtain the main window.
Call `getMainWindow` to obtain the main window of the application. Call `getMainWindow` to obtain the main window of the application.
2. Implement the immersive effect. You can use any of the following methods: 2. Implement the immersive effect. You can use any of the following methods:
...@@ -219,17 +209,15 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -219,17 +209,15 @@ To create a better video watching and gaming experience, you can use the immersi
- Method 3: Call `setLayoutFullScreen` to enable the full-screen mode for the main window layout. Call `setSystemProperties` to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window. - Method 3: Call `setLayoutFullScreen` to enable the full-screen mode for the main window layout. Call `setSystemProperties` to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window.
3. Load content for the immersive window and show it. 3. Load content for the immersive window and show it.
Call `loadContent` and `show` to load and display the content in the immersive window. Call `loadContent` and `show` to load and display the content in the immersive window.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
class MainAbility extends Ability { class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// 1. Obtain the main window of the application. // 1. Obtain the main window of the application.
var windowClass = null; let windowClass = null;
windowStage.getMainWindow((err, data) => { windowStage.getMainWindow((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
...@@ -239,7 +227,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -239,7 +227,7 @@ To create a better video watching and gaming experience, you can use the immersi
console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
// 2. Use method 1 to implement the immersive effect. // 2. Use method 1 to implement the immersive effect.
var isFullScreen = true; let isFullScreen = true;
windowClass.setFullScreen(isFullScreen, (err, data) => { windowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
...@@ -248,7 +236,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -248,7 +236,7 @@ To create a better video watching and gaming experience, you can use the immersi
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
}); });
// 2. Use method 2 to implement the immersive effect. // 2. Use method 2 to implement the immersive effect.
var names = []; let names = [];
windowClass.setSystemBarEnable(names, (err, data) => { windowClass.setSystemBarEnable(names, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err));
...@@ -257,7 +245,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -257,7 +245,7 @@ To create a better video watching and gaming experience, you can use the immersi
console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data));
}); });
// 2. Use method 3 to implement the immersive effect. // 2. Use method 3 to implement the immersive effect.
var isLayoutFullScreen = true; let isLayoutFullScreen = true;
windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
...@@ -265,7 +253,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -265,7 +253,7 @@ To create a better video watching and gaming experience, you can use the immersi
} }
console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data));
}); });
var SystemBarProperties = { let sysBarProps = {
statusBarColor: '#ff00ff', statusBarColor: '#ff00ff',
navigationBarColor: '#00ff00', navigationBarColor: '#00ff00',
// The following properties are supported since API version 7. // The following properties are supported since API version 7.
...@@ -275,7 +263,7 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -275,7 +263,7 @@ To create a better video watching and gaming experience, you can use the immersi
statusBarContentColor: '#ffffff', statusBarContentColor: '#ffffff',
navigationBarContentColor: '#ffffff' navigationBarContentColor: '#ffffff'
}; };
windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { windowClass.setSystemBarProperties(sysBarProps, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err));
return; return;
...@@ -312,14 +300,11 @@ A floating window is created based on an existing task. It is always displayed i ...@@ -312,14 +300,11 @@ A floating window is created based on an existing task. It is always displayed i
### How to Develop ### How to Develop
1. Apply for permissions. 1. Apply for permissions.
To create a floating window (of the `WindowType.TYPE_FLOAT` type), you must configure the `ohos.permission.SYSTEM_FLOAT_WINDOW` permission in the `requestPermissions` field of the `module.json5` file. For details about the file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To create a floating window (of the `WindowType.TYPE_FLOAT` type), you must configure the `ohos.permission.SYSTEM_FLOAT_WINDOW` permission in the `requestPermissions` field of the `module.json5` file. For details about the file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
> **NOTE** > **NOTE**
>
> If the task for creating the floating window is reclaimed by the system, the floating window will no longer be displayed. If you want the floating window to be displayed in such a case, apply for a [continuous task](../task-management/background-task-overview.md). > If the task for creating the floating window is reclaimed by the system, the floating window will no longer be displayed. If you want the floating window to be displayed in such a case, apply for a [continuous task](../task-management/background-task-overview.md).
```json ```json
{ {
"module": { "module": {
...@@ -339,15 +324,12 @@ A floating window is created based on an existing task. It is always displayed i ...@@ -339,15 +324,12 @@ A floating window is created based on an existing task. It is always displayed i
``` ```
2. Create a floating window. 2. Create a floating window.
Call `window.create` to create a floating window. Call `window.create` to create a floating window.
3. Set properties for the floating window. 3. Set properties for the floating window.
After the floating window is created, you can set its properties, such as the size, position, background color, and brightness. After the floating window is created, you can set its properties, such as the size, position, background color, and brightness.
4. Load content for the floating window and show it. 4. Load content for the floating window and show it.
Call `loadContent` and `show` to load and display the content in the floating window. Call `loadContent` and `show` to load and display the content in the floating window.
5. Destroy the floating window. 5. Destroy the floating window.
...@@ -362,8 +344,8 @@ A floating window is created based on an existing task. It is always displayed i ...@@ -362,8 +344,8 @@ A floating window is created based on an existing task. It is always displayed i
class MainAbility extends Ability { class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
// 2. Create a floating window. // 2. Create a floating window.
var windowClass = null; let windowClass = null;
window.create(this.context, "floatWindow", window.WindowType.TYPE_FlOAT, (err, data) => { window.create(this.context, "floatWindow", window.WindowType.TYPE_FLOAT, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the floatWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to create the floatWindow. Cause: ' + JSON.stringify(err));
return; return;
......
...@@ -11,7 +11,7 @@ For details, see [Window](../reference/apis/js-apis-window.md). ...@@ -11,7 +11,7 @@ For details, see [Window](../reference/apis/js-apis-window.md).
| Instance| API| Description| | Instance| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| Window static method| create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void | Creates a system window when `ctx` is [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md).<br>-`ctx`: application context.<br>-`type`: window type. | | Window static method| create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void | Creates a system window when `ctx` is [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md).<br>-`ctx`: application context. <br>-`type`: window type. |
| Window | resetSize(width: number, height: number, callback: AsyncCallback&lt;void&gt;): void | Changes the window size.| | Window | resetSize(width: number, height: number, callback: AsyncCallback&lt;void&gt;): void | Changes the window size.|
| Window | moveTo(x: number, y: number, callback: AsyncCallback&lt;void&gt;): void | Moves this window.| | Window | moveTo(x: number, y: number, callback: AsyncCallback&lt;void&gt;): void | Moves this window.|
| Window | loadContent(path: string, callback: AsyncCallback&lt;void&gt;): void | Loads the page content to this window.| | Window | loadContent(path: string, callback: AsyncCallback&lt;void&gt;): void | Loads the page content to this window.|
...@@ -47,14 +47,12 @@ This section uses the volume bar as an example to describe the steps for system ...@@ -47,14 +47,12 @@ This section uses the volume bar as an example to describe the steps for system
import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; import ExtensionContext from '@ohos.application.ServiceExtensionAbility';
import window from '@ohos.window'; import window from '@ohos.window';
var windowClass = null;
export default class ServiceExtensionAbility1 extends ExtensionContext { export default class ServiceExtensionAbility1 extends ExtensionContext {
onCreate(want) { onCreate(want) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want; globalThis.abilityWant = want;
// 1. Create a volume bar window. // 1. Create a volume bar window.
var windowClass = null; let windowClass = null;
window.create(this.context, "volume", window.WindowType.TYPE_VOLUME_OVERLAY, (err, data) => { window.create(this.context, "volume", window.WindowType.TYPE_VOLUME_OVERLAY, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the volume window. Cause:' + JSON.stringify(err)); console.error('Failed to create the volume window. Cause:' + JSON.stringify(err));
......
# HiSysEvent Listening<a name="EN-US_TOPIC_0000001185655868"></a> # HiSysEvent Listening
## Overview<a name="section315316685112"></a>
### Introduction<a name="section123181433335224"></a> ## Overview
### Introduction
HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to listen for power consumption events for power usage analysis. HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to listen for power consumption events for power usage analysis.
### Constraints<a name="section123181433375224"></a>
Before subscribing to system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md). ### Constraints
## Development Guidelines<a name="section315316685113"></a> Before subscribing to system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](../subsystems/subsys-dfx-hisysevent-logging-config.md).
### Available APIs<a name="section0342191810519"></a>
**Table 1** Description of EventListener APIs ## Development Guidelines
| Name| Description |
| -------- | --------- |
|int32_t HiSysEventManager::AddEventListener(std::shared_ptr&lt;HiSysEventSubscribeCallBack&gt; listener, std::vector&lt;ListenerRule&gt;&amp; rules)|Registers a listener for system events. You can listen for certain events by specifying rules.<br><br>Input arguments: <ul><li>**listener**: callback object for system events. </li><li>**rules**: rules for event listening. </li></ul>Return value:<ul><li>**0**: registration is successful. </li><li>Other values: Registration has failed.</li></ul>|
|int32_t HiSysEventManager::RemoveListener(std::shared_ptr&lt;HiSysEventSubscribeCallBack&gt; listener)|Removes the listener for system events.<br><br>Input arguments: <ul><li>**listener**: callback object for system events. </ul>Return value:<ul><li>**0**: Cancel registration is successful. </li><li>Other values: Cancel registration has failed.</li></ul>|
**Table 2** Description of ListenerRule ### Available APIs
| API| Description | **Table 1** Description of HiSysEventListener APIs
| -------- | --------- |
|ListenerRule(const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD)|Constructor used to create a **ListenerRule** object based on the event tag.<br><br>Input arguments:<ul><li>**tag**: indicates the event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits. </li><li>**ruleType**: indicates the type of the **ListenerRule** object. The value is an enum defined by **RuleType**.</li></ul>|
|ListenerRule(const std::string&amp; domain, const std::string&amp; eventName, RuleType ruleType = RuleType::WHOLE_WORD)|Constructor used to create a **ListenerRule** object based on the event domain and event name.<br><br>Input arguments: <ul><li>**domain**: indicates the event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores (&#95;). </li><li>**eventName**: indicates the event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores (&#95;). </li><li>**ruleType**: indicates the type of the **ListenerRule** object. The value is an enum defined by **RuleType**.</li></ul>|
|ListenerRule(const std::string&amp; domain, const std::string& eventName, const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD)|Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.<br><br>Input arguments:<ul><li>**tag**: indicates the event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits. </li><li>**domain**: indicates the event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores (&#95;). </li><li>**eventName**: indicates the event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores (&#95;). </li><li>**ruleType**: indicates the type of the **ListenerRule** object. The value is an enum defined by **RuleType**.</li></ul>|
**Table 3** Description of RuleType | API| Description|
| -------- | -------- |
| int32_t HiSysEventManager::AddListener(std::shared_ptr&lt;HiSysEventListener&gt; listener, std::vector&lt;ListenerRule&gt;&amp; rules) | Registers a listener for system events. You can listen for certain events by specifying rules.<br>Input arguments:<br>- **listener**: callback object for system events.<br>- **rules**: rules for event listening.<br>Return value:<br>- **0**: Registration is successful.<br>- A negative value: Registration has failed.|
| int32_t HiSysEventManager::RemoveListener(std::shared_ptr&lt;HiSysEventListener&gt; listener) | Removes the listener for system events.<br>Input arguments:<br>- **listener**: callback object for system events.<br>Return value:<br>- **0**: Canceling registration is successful.<br>- A negative value: Canceling registration has failed. |
| Value | Description | **Table 2** Description of ListenerRule
| ------------ | ------------- |
| WHOLE_WORD | Whole word matching |
| PREFIX | Prefix matching |
| REGULAR | Regular expression matching |
**Table 4** Description of HiSysEventSubscribeCallBack | API| Description|
| -------- | -------- |
| ListenerRule(const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.<br>Input arguments:<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| ListenerRule(const std::string&amp; domain, const std::string&amp; eventName, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.<br>Input arguments:<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| ListenerRule(const std::string&amp; domain, const std::string&amp; eventName, const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.<br>Input arguments:<br>- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.<br>- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.<br>- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.<br>- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
| API| Description | **Table 3** Description of RuleType
| -------- | --------- |
|void HiSysEventSubscribeCallBack::OnHandle(const std::string&amp; domain, const std::string&amp; eventName, const int eventType, const std::string&amp; eventDetail)|Provides the callback of system events.<br><br>Input arguments: <ul><li>**domain**: indicates the domain to which the event belongs. </li><li>**eventName**: indicates the event name. </li><li>**eventType**: indicates the event type. </li><li>**eventDetail**: indicates the event information, in JSON format. </li></ul>Return value:<br>None.|
### Development Example<a name="section123181432175110"></a> | Value| Description|
| -------- | -------- |
| WHOLE_WORD | Whole word matching|
| PREFIX | Prefix matching|
| REGULAR | Regular expression matching|
C++ **Table 4** Description of HiSysEventListener
1. Develop the source code. | API| Description|
| -------- | -------- |
| void HiSysEventListener::OnEvent(std::shared_ptr&lt;HiSysEventRecord&gt; sysEvent) | Callback object for system events.<br>Input arguments:<br>- **sysEvent**: real-time system events.<br>Return value:<br>None.|
| void HiSysEventListener::OnServiceDied() | Callback object for service exceptions.<br>Input arguments:<br>None.<br>Return value:<br>None.|
**Table 5** Description of HiSysEventRecord
| API| Description|
| -------- | -------- |
|std::string HiSysEventRecord::AsJson()|Obtains the content of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Content of the system event.|
|std::string HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Domain name of the system event.|
|std::string HiSysEventRecord::GetEventName()|Obtains the name of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Name of the system event.|
|HiSysEvent::EventType HiSysEventRecord::GetEventType()|Obtains the type of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Type of the system event.|
|std::string HiSysEventRecord::GetLevel()|Obtains the level of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Level of the system event.|
|std::string HiSysEventRecord::GetTag()|Obtains the tag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Tag of the system event.|
|std::string HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Time zone, in the format of **+0800**.|
|int HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Distributed call chain tracing flag.|
|int64_t HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Process ID.|
|int64_t HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>Thread ID.|
|int64_t HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.<br>Input arguments:<br>None.<br>Return value:<br>User ID.|
|uint64_t HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Parent span ID of the distributed call chain tracing task.|
|uint64_t HiSysEventRecord::GetSpandId()|Obtains the span ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>Span ID of the distributed call chain tracing task.|
|uint64_t HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.<br>Input arguments:<br>None.<br>Return value:<br>Timestamp of the system event.|
|uint64_t HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.<br>Input arguments:<br>None.<br>Return value:<br>ID of the distributed call chain tracing task.|
|void HiSysEventRecord::GetParamNames(std::vector&lt;std::string&gt;&amp; params)|Obtains all key names of a system event.<br>Input arguments:<br>- **params**: key name array reference.<br>Return value:<br>None.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, int64_t&amp; value)|Parses the value of the **param** key in a system event into an int64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, uint64_t&amp; value)|Parses the value of the **param** key in a system event into a uint64\_t value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, double&amp; value)|Parses the value of the **param** key in a system event into a double value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::string&amp; value)|Parses the value of the **param** key in a system event into a string value.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;int64_t&gt;&amp; value)|Parses the value of the **param** key in a system event into an int64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: int64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;uint64_t&gt;&amp; value)|Parses the value of the **param** key in a system event into a uint64\_t array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: uint64\_t array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;double&gt;&amp; value)|Parses the value of the **param** key in a system event into a double array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: double array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
|int HiSysEventRecord::GetParamValue(const std::string&amp; param, std::vector&lt;std::string&gt;&amp; value)|Parses the value of the **param** key in a system event into a string array.<br>Input arguments:<br>- **param**: key name.<br>- **value**: std::string array reference.<br>Return value:<br>- **0**: Parsing is successful.<br>- **-1**: Parsing failed due to initialization error.<br>- **-2**: Parsing failed due to nonexistent key name.<br>- **-3**: Parsing failed due to type mismatch.|
## How to Develop
### **C++**
The following provides an example of how to use C++ APIs of **HiSysEvent**.
1. Develop the source code.
Import the **DemoListener.h** header file, which contains the **DemoListener** class for implementing the custom event callback. Import the **DemoListener.h** header file, which contains the **DemoListener** class for implementing the custom event callback.
``` ```
#ifndef DEMO_LISTENER_H #ifndef DEMO_LISTENER_H
#define DEMO_LISTENER_H #define DEMO_LISTENER_H
#include "hisysevent_subscribe_callback.h" #include "hisysevent_listener.h"
#include <string> #include <string>
class DemoListener : public OHOS::HiviewDFX::HiSysEventSubscribeCallBack { class DemoListener : public OHOS::HiviewDFX::HiSysEventListener {
public: public:
explicit DemoListener() : HiSysEventSubscribeCallBack() {} explicit DemoListener() : HiSysEventListener() {}
void OnHandle(const std::string& domain, const std::string& eventName, const int eventType,
const std::string& eventDetail);
virtual ~DemoListener() {} virtual ~DemoListener() {}
public:
void OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent);
void OnServiceDied(); void OnServiceDied();
}; };
...@@ -78,10 +116,12 @@ C++ ...@@ -78,10 +116,12 @@ C++
#include <iostream> #include <iostream>
void DemoListener::OnHandle(const std::string& domain, const std::string& eventName, void DemoListener::OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent)
const int eventType, const std::string& eventDetail)
{ {
std::cout << eventDetail << std::endl; if (sysEvent == nullptr) {
return;
}
std::cout << sysEvent.AsJson() << std::endl;
} }
void DemoListener::OnServiceDied() void DemoListener::OnServiceDied()
...@@ -94,13 +134,7 @@ C++ ...@@ -94,13 +134,7 @@ C++
Call the **AddEventListener** API of the **HiSysEventManager** class to add a listener for system events. Call the **AddEventListener** API of the **HiSysEventManager** class to add a listener for system events.
``` ```
std::shared_ptr<DemoListener> demoListener = nullptr; auto demoListener = std::make_shared<DemoListener>();
try {
demoListener = std::make_shared<DemoListener>();
} catch(...) {
// Catch exception thrown by make_shared
}
if (demoListener != nullptr) {
// Add a ListenerRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD). // Add a ListenerRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
ListenerRule tagRule("dfx"); ListenerRule tagRule("dfx");
// Add a ListenerRule object based on the event tag, with RuleType set as REGULAR. // Add a ListenerRule object based on the event tag, with RuleType set as REGULAR.
...@@ -112,13 +146,14 @@ C++ ...@@ -112,13 +146,14 @@ C++
sysRules.push_back(regRule); sysRules.push_back(regRule);
sysRules.push_back(domainNameRule); sysRules.push_back(domainNameRule);
HiSysEventManager::AddEventListener(demoListener, sysRules); HiSysEventManager::AddEventListener(demoListener, sysRules);
}
``` ```
2. Configure the **BUILD.gn** file. 2. Configure the **BUILD.gn** file.
In the **BUILD.gn** file, add the **libhisysevent** and **libhisyseventmanager** libraries that depend on the **hisysevent_native** component.
In the **BUILD.gn** file, add the **libhisyseventmanager** library that depends on the **hisysevent\_native** component.
``` ```
external_deps = [ "hisysevent_native:libhisyseventmanager", ] external_deps = [
"hisysevent_native:libhisysevent",
"hisysevent_native:libhisyseventmanager",
]
``` ```
# HiSysEvent Query<a name="EN-US_TOPIC_0000001231455461"></a> # HiSysEvent Query
## Overview<a name="section279684125212"></a>
HiSysEvent provides an API for you to query system events. You can query concerned events by specifying search criteria. For example, for a power consumption module, you can query required system events for analysis. ## Overview
## Development Guidelines<a name="section315316761113"></a> HiSysEvent allows you to query system events by specifying search criteria. For example, for a power consumption module, you can query required system events for analysis.
### Available APIs<a name="section03869128521"></a>
**Table 1** Description of the HiSysEvent query API ## Development Guidelines
| Name| Description |
| -------- | --------- |
| int32_t HiSysEventManager::QueryHiSysEvent(struct QueryArg&amp; queryArg, std::vector&lt;QueryRule&gt;&amp; queryRules, std::shared_ptr&lt;HiSysEventQueryCallBack&gt; queryCallBack) | Queries system events by specifying search criteria such as the time segment, event domain, and event name.<br><br>Input arguments:<ul><li>**queryArg**: event query parameter. </li><li>**queryRules**: event filtering rules. </li><li>**queryRules**: callback object for query results. </li></ul>Return value:<ul><li>**0**: The query is successful. </li><li>Other values: The query has failed.</li></ul> |
### Available APIs
**Table 2** Description of QueryArg > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> For details about the **HiSysEventRecord** argument in the **OnQuery()** method of **HiSysEventQueryCallback**, see Table 5 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
| Attribute| Description | **Table 1** Description of the HiSysEvent query API
| -------- | --------- |
| API| Description|
| -------- | -------- |
| int32_t HiSysEventManager::Query(struct QueryArg&amp; arg, std::vector&lt;QueryRule&gt;&amp; rules, std::shared_ptr&lt;HiSysEventQueryCallback&gt; callback) | Queries system events by specifying search criteria such as the time segment, event domain, and event name.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
**Table 2** Description of QueryArg
| Attribute| Description|
| -------- | -------- |
| beginTime | Start time, in the **long long int** format.| | beginTime | Start time, in the **long long int** format.|
| endTime | End time, in the **long long int** format.| | endTime | End time, in the **long long int** format.|
| maxEvents | Maximum number of returned events, in the **int** format.| | maxEvents | Maximum number of returned events, in the **int** format.|
**Table 3** Description of QueryRule **Table 3** Description of QueryRule
| API| Description | | API| Description|
| -------- | --------- | | -------- | -------- |
| QueryRule(const std::string& domain, const std::vector&lt;std::string&gt;& eventList) | Constructor used to create a **QueryRule** object.<br><br>Input arguments:<ul><li>**domain: domain to which the event of the **QueryRule** object belongs, in the **string** format. By default, an empty string indicates that the domain is successfully matched. </li><li>**eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.</li></ul> | | QueryRule(const std::string&amp; domain, const std::vector&lt;std::string&gt;&amp; eventList) | Constructor used to create a **QueryRule** object.<br>Input arguments:<br>- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.<br>- **eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.|
**Table 4** Description of HiSysEventQueryCallBack **Table 4** Description of HiSysEventQueryCallback
| API| Description | | API| Description|
| -------- | --------- | | -------- | -------- |
| void HiSysEventQueryCallBack::OnQuery(const ::std::vector&lt;std::string&gt;&amp; sysEvent, const ::std::vector&lt;int64_t&gt;&amp; seq) | Callback object for event query.<br><br>Input arguments:<ul><li>**sysEvent**: event set. </li><li>**seq**: event sequence set. </li></ul>Return value:<br>None.| | void HiSysEventQueryCallback::OnQuery(std::shared_ptr&lt;std::vector&lt;HiSysEventRecord&gt;&gt; sysEvents) | Callback object for event query.<br>Input arguments:<br>- **sysEvents**: event list.<br>Return value:<br>None.|
| void HiSysEventQueryCallBack::OnComplete(int32_t reason, int32_t total) | Callback object for completion of event query.<br><br>Input arguments:<ul><li>**reason**: reason for completion of event query. The default value is **0**. </li><li>**total**: total number of events returned in this query. </li></ul>Return value:<br>None.| | void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total) | Callback object for completion of event query.<br>Input arguments:<br>- **reason**: reason for completion of event query. The default value is **0**.<br>- **total**: total number of events returned in this query.<br>Return value:<br>None.|
### Development Example<a name="section14286111855212"></a> ### How to Develop
C++ **C++**
1. Develop the source code. 1. Develop the source code.
Import the corresponding header file:
- Import the corresponding header file: ```
#include "hisysevent_manager.h"
hisysevent\_manager.h ```
- Implement the callback API.
void HiSysEventQueryCallBack::OnQuery\(const ::std::vector&lt;std::string&gt;& sysEvent, const ::std::vector<int64\_t\>& seq\) Implement the callback API.
void HiSysEventQueryCallBack::OnComplete\(int32\_t reason, int32\_t total\) ```
void HiSysEventQueryCallback::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents)
void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total)
```
- Invoke the query API in the corresponding service logic. Invoke the query API in the corresponding service logic.
HiSysEventManager::QueryHiSysEvent\(struct QueryArg& queryArg, std::vector<QueryRule\>& queryRules, std::shared\_ptr<HiSysEventQueryCallBack\> queryCallBack\) ```
HiSysEventManager::Query(struct QueryArg& queryArg,
std::vector<QueryRule>& queryRules, std::shared_ptr<HiSysEventQueryCallback> queryCallBack)
```
In this example, you'll query all system events.
``` ```
// In this example, you'll query all system events.
#include "hisysevent_manager.h" #include "hisysevent_manager.h"
#include <iostream> #include <iostream>
namespace OHOS { namespace OHOS {
namespace HiviewDFX { namespace HiviewDFX {
// Implement the query callback API. // Implement the query callback API.
void HiSysEventToolQuery::OnQuery(const ::std::vector<std::string>& sysEvent, void HiSysEventToolQuery::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents)
const ::std::vector<int64_t>& seq)
{ {
for_each(sysEvent.cbegin(), sysEvent.cend(), [](const std::string &tmp) { if (sysEvents == nullptr) {
std::cout << tmp << std::endl; return;
}
for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
std::cout << event.AsJson() << std::endl;
}); });
} }
...@@ -81,23 +94,18 @@ C++ ...@@ -81,23 +94,18 @@ C++
} // namespace OHOS } // namespace OHOS
// Invoke the query callback API to obtain system events. // Invoke the query callback API to obtain system events.
std::shared_ptr<HiSysEventToolQuery> queryCallBack = nullptr; auto queryCallBack = std::make_shared<HiSysEventToolQuery>();
try {
queryCallBack = std::make_shared<HiSysEventToolQuery>();
} catch(...) {
// Catch exception thrown by make_shared
}
if (queryCallBack != nullptr) {
struct QueryArg args(clientCmdArg.beginTime, clientCmdArg.endTime, clientCmdArg.maxEvents); struct QueryArg args(clientCmdArg.beginTime, clientCmdArg.endTime, clientCmdArg.maxEvents);
std::vector<QueryRule> rules; std::vector<QueryRule> rules;
HiSysEventManager::QueryHiSysEvent(args, rules, queryCallBack); HiSysEventManager::QueryHiSysEvent(args, rules, queryCallBack);
}
``` ```
2. Modify the **BUILD.gn** file. 2. Modify the **BUILD.gn** file.
In the **BUILD.gn** file, add the **libhisysevent** and **libhisyseventmanager** libraries that depend on the **hisysevent_native** component.
In the **BUILD.gn** file, add the **libhisyseventmanager** library that depends on the **hisysevent\_native** component.
``` ```
external_deps = [ "hisysevent_native:libhisyseventmanager", ] external_deps = [
"hisysevent_native:libhisysevent",
"hisysevent_native:libhisyseventmanager",
]
``` ```
...@@ -17,7 +17,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -17,7 +17,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
| Option| Description| | Option| Description|
| -------- | -------- | | -------- | -------- |
| -r | Subscribes to real-time system events based on the default settings. When this option is specified, any real-time system event will be printed on the console.| | -r | Subscription to real-time system events based on the default settings. When this option is specified, any real-time system event will be printed on the console.|
- Command for enabling the debugging mode: - Command for enabling the debugging mode:
...@@ -29,7 +29,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -29,7 +29,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
| Option| Description| | Option| Description|
| -------- | -------- | | -------- | -------- |
| -d | Subscribes to real-time system events in debugging mode.| | -d | Subscription to real-time system events in debugging mode.|
- Command for subscribing to real-time system events by event tag: - Command for subscribing to real-time system events by event tag:
...@@ -96,7 +96,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -96,7 +96,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
| Option| Description| | Option| Description|
| -------- | -------- | | -------- | -------- |
| -l | Queries historical system events based on the default settings. A maximum of 1,000 latest system events will be returned.| | -l | Query of historical system events based on the default settings. A maximum of 10,000 system events will be returned.|
- Command for querying historical system events within the specified period of time: - Command for querying historical system events within the specified period of time:
...@@ -130,7 +130,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -130,7 +130,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
| Option| Description| | Option| Description|
| -------- | -------- | | -------- | -------- |
| -m | Maximum number of historical system events that can be queried. The value ranges from **0** to **1000**. The number of returned system events is not more than the value of this parameter.| | -m | Maximum number of historical system events that can be queried. The number of returned system events is not more than the value of this parameter.|
Example: Example:
...@@ -151,7 +151,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin** ...@@ -151,7 +151,7 @@ The HiSysEvent tool is a command line tool preconfigured in the **/system/bin**
| Option| Description| | Option| Description|
| -------- | -------- | | -------- | -------- |
| -v | Used with the subscription command **-r** and query command **-l**. If system event validity check is enabled, invalid content contained in system events will be highlighted in red.| | -v | Used with the **-r** and **-l** commands. If system event validity check is enabled, invalid content contained in system events will be highlighted in red.|
Example: Example:
......
...@@ -97,7 +97,7 @@ Security subsystem ...@@ -97,7 +97,7 @@ Security subsystem
[security_device_auth](https://gitee.com/openharmony/security_device_auth) [security_device_auth](https://gitee.com/openharmony/security_device_auth)
[security_permission](https://gitee.com/openharmony/security_permission) [security_permission_lite](https://gitee.com/openharmony/security_permission_lite)
[security_device_security_level](https://gitee.com/openharmony/security_device_security_level) [security_device_security_level](https://gitee.com/openharmony/security_device_security_level)
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
![IDL-interface-description](./figures/IDL-interface-description.png) ![IDL-interface-description](./figures/IDL-interface-description.png)
OpenHarmony IDL接口描述语言主要用于: **OpenHarmony IDL接口描述语言主要用于:**
- 声明系统服务对外提供的服务接口,根据接口声明在编译时生成跨进程调用(IPC)或跨设备调用(RPC)的代理(Proxy)和桩(Stub)的C/C++代码或JS/TS代码。 - 声明系统服务对外提供的服务接口,根据接口声明在编译时生成跨进程调用(IPC)或跨设备调用(RPC)的代理(Proxy)和桩(Stub)的C/C++代码或JS/TS代码。
...@@ -17,7 +17,7 @@ OpenHarmony IDL接口描述语言主要用于: ...@@ -17,7 +17,7 @@ OpenHarmony IDL接口描述语言主要用于:
![IPC-RPC-communication-model](./figures/IPC-RPC-communication-model.png) ![IPC-RPC-communication-model](./figures/IPC-RPC-communication-model.png)
使用OpenHarmony IDL接口描述语言声明接口具有以下优点: **使用OpenHarmony IDL接口描述语言声明接口具有以下优点:**
- OpenHarmony IDL中是以接口的形式定义服务,可以专注于定义而隐藏实现细节。 - OpenHarmony IDL中是以接口的形式定义服务,可以专注于定义而隐藏实现细节。
...@@ -59,7 +59,7 @@ sequenceable namespace.typename ...@@ -59,7 +59,7 @@ sequenceable namespace.typename
sequenceable a.b..C.D sequenceable a.b..C.D
``` ```
上述声明在生成的的C++头文件中将被解析为如下代码: 上述声明在生成的的C++头文件中将被解析为如下代码:
```cpp ```cpp
#include “a/b/d.h” #include “a/b/d.h”
...@@ -81,15 +81,15 @@ import MySequenceable from "./my_sequenceable" ...@@ -81,15 +81,15 @@ import MySequenceable from "./my_sequenceable"
需要注意的是,IDL并不负责该类型的代码实现,仅仅按照指定的形式引入该头文件或import指定模块,并使用该类型,因此开发者需要自行保证引入目录、命名空间及类型的正确性。 需要注意的是,IDL并不负责该类型的代码实现,仅仅按照指定的形式引入该头文件或import指定模块,并使用该类型,因此开发者需要自行保证引入目录、命名空间及类型的正确性。
#### 接口类型 #### 接口类型
接口类型是指OpenHarmony IDL文件中定义的接口。对于当前IDL文件中定义的接口,可以直接使用它作为方法参数类型或返回值类型。而在其它OpenHarmony IDL文件中定义的接口,则需要在文件的头部进行前置声明。 接口类型是指OpenHarmony IDL文件中定义的接口。对于当前IDL文件中定义的接口,可以直接使用它作为方法参数类型或返回值类型。而在其它OpenHarmony IDL文件中定义的接口,则需要在文件的头部进行前置声明。
C++中声明的形式与sequenceable类型相似,具体而言可以有如下形式: C++中声明的形式与sequenceable类型相似,具体而言可以有如下形式:
```cpp ```cpp
interface includedir..namespace.typename interface includedir..namespace.typename
``` ```
TS中声明的形式,具体而言可以有如下形式: TS中声明的形式,具体而言可以有如下形式:
```ts ```ts
interface namespace.interfacename interface namespace.interfacename
...@@ -495,7 +495,7 @@ function connectAbility: void { ...@@ -495,7 +495,7 @@ function connectAbility: void {
开发者可以通过 IPC 接口,将某个类从一个进程发送至另一个进程。但是,必须确保 IPC 通道的另一端可使用该类的代码,并且该类必须支持marshalling和unmarshalling方法。OpenHarmony 需要通过该marshalling和unmarshalling方法将对象序列化和反序列化成各进程能识别的对象。 开发者可以通过 IPC 接口,将某个类从一个进程发送至另一个进程。但是,必须确保 IPC 通道的另一端可使用该类的代码,并且该类必须支持marshalling和unmarshalling方法。OpenHarmony 需要通过该marshalling和unmarshalling方法将对象序列化和反序列化成各进程能识别的对象。
如需创建支持sequenceable 类型数据,开发者必须执行以下操作: **如需创建支持sequenceable 类型数据,开发者必须执行以下操作:**
1. 实现marshalling方法,它会获取对象的当前状态并将其序列化后写入Parcel。 1. 实现marshalling方法,它会获取对象的当前状态并将其序列化后写入Parcel。
2. 实现unmarshalling方法,它会从Parcel中反序列化出对象。 2. 实现unmarshalling方法,它会从Parcel中反序列化出对象。
......
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
- 工具 - 工具
- [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md)
- 示例教程 - 示例教程
- [示例代码](https://gitee.com/openharmony/app_samples/blob/master/README_zh.md) - [示例代码](https://gitee.com/openharmony/applications_app_samples/blob/master/README_zh.md)
- [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md)
- API参考 - API参考
- [组件参考(基于TS扩展的声明式开发范式)](reference/arkui-ts/Readme-CN.md) - [组件参考(基于TS扩展的声明式开发范式)](reference/arkui-ts/Readme-CN.md)
......
...@@ -41,7 +41,7 @@ ...@@ -41,7 +41,7 @@
"module": { "module": {
"abilities": [ "abilities": [
{ {
"continuable": true, "continuable": true
} }
] ]
} }
...@@ -62,7 +62,7 @@ ...@@ -62,7 +62,7 @@
"module": { "module": {
"abilities": [ "abilities": [
{ {
"launchType": "standard", "launchType": "standard"
} }
] ]
} }
...@@ -76,7 +76,7 @@ ...@@ -76,7 +76,7 @@
"module": { "module": {
"abilities": [ "abilities": [
{ {
"launchType": "singleton", "launchType": "singleton"
} }
] ]
} }
......
...@@ -47,7 +47,7 @@ DevEco Studio工具是OpenHarmony应用开发的推荐IDE工具。 ...@@ -47,7 +47,7 @@ DevEco Studio工具是OpenHarmony应用开发的推荐IDE工具。
### 示例教程 ### 示例教程
我们提供了[Sample工程](https://gitee.com/openharmony/app_samples/blob/master/README_zh.md)[Codelab](https://gitee.com/openharmony/codelabs/blob/master/README.md)这两种形式的示例教程,为开发者提供更丰富的开发参考,辅助开发者理解功能逻辑,提升开发效率。 我们提供了[Sample工程](https://gitee.com/openharmony/applications_app_samples/blob/master/README_zh.md)[Codelab](https://gitee.com/openharmony/codelabs/blob/master/README.md)这两种形式的示例教程,为开发者提供更丰富的开发参考,辅助开发者理解功能逻辑,提升开发效率。
### API参考 ### API参考
......
...@@ -48,7 +48,7 @@ DevEco Studio工具是OpenHarmony应用开发的推荐IDE工具。 ...@@ -48,7 +48,7 @@ DevEco Studio工具是OpenHarmony应用开发的推荐IDE工具。
### 示例教程 ### 示例教程
我们提供了[Sample工程](https://gitee.com/openharmony/app_samples/blob/master/README_zh.md)[Codelab](https://gitee.com/openharmony/codelabs/blob/master/README.md)这两种形式的示例教程,为开发者提供更丰富的开发参考,辅助开发者理解功能逻辑,提升开发效率。 我们提供了[Sample工程](https://gitee.com/openharmony/applications_app_samples/blob/master/README_zh.md)[Codelab](https://gitee.com/openharmony/codelabs/blob/master/README.md)这两种形式的示例教程,为开发者提供更丰富的开发参考,辅助开发者理解功能逻辑,提升开发效率。
### API参考 ### API参考
......
...@@ -94,9 +94,16 @@ ...@@ -94,9 +94,16 @@
```js ```js
// 获取context // 获取context
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext() let context = featureAbility.getContext();
let preferences = null;
let promise = data_preferences.getPreferences(context, 'mystore'); let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get preferences.");
})
``` ```
Stage模型示例: Stage模型示例:
...@@ -104,14 +111,21 @@ ...@@ -104,14 +111,21 @@
```ts ```ts
// 获取context // 获取context
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
let context = null let context = null;
let preferences = null;
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context context = this.context;
} }
} }
let promise = data_preferences.getPreferences(context, 'mystore'); let promise = data_preferences.getPreferences(context, 'mystore');
promise.then((pref) => {
preferences = pref;
}).catch((err) => {
console.info("Failed to get preferences.");
})
``` ```
3. 存入数据。 3. 存入数据。
...@@ -119,16 +133,12 @@ ...@@ -119,16 +133,12 @@
使用put方法保存数据到缓存的实例中。 使用put方法保存数据到缓存的实例中。
```js ```js
promise.then((preferences) => {
let putPromise = preferences.put('startup', 'auto'); let putPromise = preferences.put('startup', 'auto');
putPromise.then(() => { putPromise.then(() => {
console.info("Succeeded in putting the value of 'startup'."); console.info("Succeeded in putting the value of 'startup'.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to put the value of 'startup'. Cause: " + err); console.info("Failed to put the value of 'startup'. Cause: " + err);
}) })
}).catch((err) => {
console.info("Failed to get preferences.");
})
``` ```
4. 读取数据。 4. 读取数据。
...@@ -136,16 +146,12 @@ ...@@ -136,16 +146,12 @@
使用get方法读取数据。 使用get方法读取数据。
```js ```js
promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default'); let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => { getPromise.then((value) => {
console.info("The value of 'startup' is " + value); console.info("The value of 'startup' is " + value);
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the value of 'startup'. Cause: " + err); console.info("Failed to get the value of 'startup'. Cause: " + err);
}) })
}).catch((err) => {
console.info("Failed to get preferences.")
});
``` ```
5. 数据持久化。 5. 数据持久化。
...@@ -165,7 +171,7 @@ ...@@ -165,7 +171,7 @@
console.info("The key" + key + " changed."); console.info("The key" + key + " changed.");
} }
preferences.on('change', observer); preferences.on('change', observer);
// 数据产生变更,由'auto'变为'manual' // 数据产生变更,由'auto'变为'manual'
preferences.put('startup', 'manual', function (err) { preferences.put('startup', 'manual', function (err) {
if (err) { if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err); console.info("Failed to put the value of 'startup'. Cause: " + err);
......
...@@ -196,14 +196,38 @@ ...@@ -196,14 +196,38 @@
(3) 创建数据库。 (3) 创建数据库。
示例代码如下 FA模型示例
```js ```js
import data_rdb from '@ohos.data.rdb' import data_rdb from '@ohos.data.rdb'
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "RdbTest.db" }
data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
```
Stage模型示例:
```ts
import data_rdb from '@ohos.data.rdb'
// 获取context
import Ability from '@ohos.application.Ability'
let context = null
class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
context = this.context
}
}
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "rdbstore.db" } const STORE_CONFIG = { name: "rdbstore.db" }
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST) rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.') console.info('create table done.')
}) })
......
# 示例服务器开发概述 # 示例服务器开发概述
示例服务器提供一个简易的升级包部署的服务器实例参考,用于升级服务子系统的辅助验证环境搭建 示例服务器提供一个简易的升级包部署的服务器实例参考,用于搭建升级服务子系统的辅助验证环境
## 基本概念 ## 基本概念
......
...@@ -6,10 +6,10 @@ ...@@ -6,10 +6,10 @@
设备类型分为default(默认设备)、tablet、tv、wearable等,有多种查询设备类型的方式。 设备类型分为default(默认设备)、tablet、tv、wearable等,有多种查询设备类型的方式。
1. 通过命令行的方式查询设备类型。 1. 通过命令行的方式查询设备类型。
通过命令行查询指定系统参数(const.build.characteristics)进而确定设备类型,详见[系统参数介绍](../../../device-dev/subsystems/subsys-boot-syspara.md) 通过命令行查询指定系统参数(const.build.characteristics)进而确定设备类型,详见[系统参数介绍](../../../device-dev/subsystems/subsys-boot-init-sysparam.md)
```ts ```bash
# 方法一 # 方法一
hdc shell param get "const.build.characteristics" hdc shell param get "const.build.characteristics"
# 方法二 # 方法二
......
...@@ -8,7 +8,7 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 ...@@ -8,7 +8,7 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以
在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioCapturer的状态变更。因为针对AudioCapturer的某些操作,仅在音频采集器在固定状态时才能执行。如果应用在音频采集器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。 在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioCapturer的状态变更。因为针对AudioCapturer的某些操作,仅在音频采集器在固定状态时才能执行。如果应用在音频采集器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。
详细API含义可参考:[音频管理API文档AudioCapturer](../reference/apis/js-apis-audio.md) 详细API含义可参考:[音频管理API文档AudioCapturer](../reference/apis/js-apis-audio.md#audiocapturer8)
**图1** 音频采集状态机 **图1** 音频采集状态机
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
## 开发步骤 ## 开发步骤
详细API含义可参考:[媒体服务API文档AudioPlayer](../reference/apis/js-apis-media.md) 详细API含义可参考:[媒体服务API文档AudioPlayer](../reference/apis/js-apis-media.md#audioplayer)
### 全流程场景 ### 全流程场景
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
## 开发步骤 ## 开发步骤
详细API含义可参考:[媒体服务API文档AudioRecorder](../reference/apis/js-apis-media.md) 详细API含义可参考:[媒体服务API文档AudioRecorder](../reference/apis/js-apis-media.md#audiorecorder)
### 全流程场景 ### 全流程场景
......
...@@ -6,7 +6,7 @@ AudioStreamManager提供了音频流管理的方法。开发者可以通过本 ...@@ -6,7 +6,7 @@ AudioStreamManager提供了音频流管理的方法。开发者可以通过本
### 工作流程 ### 工作流程
在进行应用开发的过程中,开发者需要使用getStreamManager()创建一个AudioStreamManager实例,进而通过该实例管理音频流。开发者可通过调用on('audioRendererChange')、on('audioCapturerChange')监听音频播放应用和音频录制应用,在应用状态变化、设备变化、音频属性变化时获得通知。同时可通过off('audioRendererChange')、off('audioCapturerChange')取消相关事件的监听。与此同时,开发者可以通过调用(可选)使用getCurrentAudioRendererInfoArray()获取当前音频播放应用的音频流唯一ID、音频播放客户端的UID、音频状态等信息,同理可调用getCurrentAudioCapturerInfoArray()获取音频录制应用的信息。其具体调用关系可参考音频流管理调用关系图。 在进行应用开发的过程中,开发者需要使用getStreamManager()创建一个AudioStreamManager实例,进而通过该实例管理音频流。开发者可通过调用on('audioRendererChange')、on('audioCapturerChange')监听音频播放应用和音频录制应用,在应用状态变化、设备变化、音频属性变化时获得通知。同时可通过off('audioRendererChange')、off('audioCapturerChange')取消相关事件的监听。与此同时,开发者可以通过调用(可选)使用getCurrentAudioRendererInfoArray()获取当前音频播放应用的音频流唯一ID、音频播放客户端的UID、音频状态等信息,同理可调用getCurrentAudioCapturerInfoArray()获取音频录制应用的信息。其具体调用关系可参考音频流管理调用关系图。
详细API含义可参考:[音频管理API文档AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9) 详细API含义可参考:[音频管理API文档AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9)
......
...@@ -26,7 +26,7 @@ import image from '@ohos.multimedia.image' ...@@ -26,7 +26,7 @@ import image from '@ohos.multimedia.image'
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
//创建CameraManager对象 // 创建CameraManager对象
let cameraManager let cameraManager
await camera.getCameraManager(globalThis.Context, (err, manager) => { await camera.getCameraManager(globalThis.Context, (err, manager) => {
if (err) { if (err) {
...@@ -37,13 +37,13 @@ await camera.getCameraManager(globalThis.Context, (err, manager) => { ...@@ -37,13 +37,13 @@ await camera.getCameraManager(globalThis.Context, (err, manager) => {
cameraManager = manager cameraManager = manager
}) })
//注册回调函数监听相机状态变化,获取状态变化的相机信息 // 注册回调函数监听相机状态变化,获取状态变化的相机信息
cameraManager.on('cameraStatus', (cameraStatusInfo) => { cameraManager.on('cameraStatus', (cameraStatusInfo) => {
console.log('camera : ' + cameraStatusInfo.camera.cameraId); console.log('camera : ' + cameraStatusInfo.camera.cameraId);
console.log('status: ' + cameraStatusInfo.status); console.log('status: ' + cameraStatusInfo.status);
}) })
//获取相机列表 // 获取相机列表
let cameraArray let cameraArray
await cameraManager.getCameras((err, cameras) => { await cameraManager.getCameras((err, cameras) => {
if (err) { if (err) {
...@@ -55,20 +55,20 @@ await cameraManager.getCameras((err, cameras) => { ...@@ -55,20 +55,20 @@ await cameraManager.getCameras((err, cameras) => {
}) })
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) //获取相机ID console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // 获取相机ID
console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) //获取相机位置 console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // 获取相机位置
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) //获取相机类型 console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // 获取相机类型
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) //获取相机连接类型 console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // 获取相机连接类型
} }
//创建相机输入流 // 创建相机输入流
let cameraInput let cameraInput
await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => { await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
console.log('Promise returned with the CameraInput instance'); console.log('Promise returned with the CameraInput instance');
cameraInput = input cameraInput = input
}) })
//创建预览输出流 // 创建预览输出流
let previewOutput let previewOutput
camera.createPreviewOutput((globalThis.surfaceId), (err, output) => { camera.createPreviewOutput((globalThis.surfaceId), (err, output) => {
if (err) { if (err) {
...@@ -79,11 +79,11 @@ camera.createPreviewOutput((globalThis.surfaceId), (err, output) => { ...@@ -79,11 +79,11 @@ camera.createPreviewOutput((globalThis.surfaceId), (err, output) => {
previewOutput = output previewOutput = output
}); });
//创建ImageReceiver对象,并设置照片参数 // 创建ImageReceiver对象,并设置照片参数
let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
//获取照片显示SurfaceId // 获取照片显示SurfaceId
let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
//创建拍照输出流 // 创建拍照输出流
let photoOutput let photoOutput
camera.createPhotoOutput((photoSurfaceId), (err, output) => { camera.createPhotoOutput((photoSurfaceId), (err, output) => {
if (err) { if (err) {
...@@ -94,7 +94,7 @@ camera.createPhotoOutput((photoSurfaceId), (err, output) => { ...@@ -94,7 +94,7 @@ camera.createPhotoOutput((photoSurfaceId), (err, output) => {
photoOutput = output photoOutput = output
}); });
//创建视频录制的参数 // 创建视频录制的参数
let videoProfile = { let videoProfile = {
audioBitrate : 48000, audioBitrate : 48000,
audioChannels : 2, audioChannels : 2,
...@@ -116,13 +116,13 @@ let videoConfig = { ...@@ -116,13 +116,13 @@ let videoConfig = {
location : { latitude : 30, longitude : 130 }, location : { latitude : 30, longitude : 130 },
} }
//创建录像输出流 // 创建录像输出流
let videoRecorder let videoRecorder
await media.createVideoRecorder().then((recorder) => { await media.createVideoRecorder().then((recorder) => {
console.log('createVideoRecorder called') console.log('createVideoRecorder called')
videoRecorder = recorder videoRecorder = recorder
}) })
//设置视频录制的参数 // 设置视频录制的参数
await videoRecorder.prepare(videoConfig) await videoRecorder.prepare(videoConfig)
//获取录像SurfaceId //获取录像SurfaceId
await videoRecorder.getInputSurface().then((id) => { await videoRecorder.getInputSurface().then((id) => {
...@@ -132,7 +132,7 @@ await videoRecorder.getInputSurface().then((id) => { ...@@ -132,7 +132,7 @@ await videoRecorder.getInputSurface().then((id) => {
``` ```
videoRecorder详细创建方法可参考:[视频录制开发指导](./video-recorder.md) videoRecorder详细创建方法可参考:[视频录制开发指导](./video-recorder.md)
```js ```js
//创建VideoOutput对象 // 创建VideoOutput对象
let videoOutput let videoOutput
camera.createVideoOutput((surfaceId), (err, output) => { camera.createVideoOutput((surfaceId), (err, output) => {
if (err) { if (err) {
...@@ -148,14 +148,14 @@ camera.createVideoOutput((surfaceId), (err, output) => { ...@@ -148,14 +148,14 @@ camera.createVideoOutput((surfaceId), (err, output) => {
#### 参数设置 #### 参数设置
```js ```js
//判断设备是否支持闪光灯 // 判断设备是否支持闪光灯
let flashStatus let flashStatus
await cameraInput.hasFlash().then((status) => { await cameraInput.hasFlash().then((status) => {
console.log('Promise returned with the flash light support status:' + status); console.log('Promise returned with the flash light support status:' + status);
flashStatus = status flashStatus = status
}) })
if(flashStatus) { if(flashStatus) {
//判断是否支持自动闪光灯模式 // 判断是否支持自动闪光灯模式
let flashModeStatus let flashModeStatus
cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => {
if (err) { if (err) {
...@@ -166,7 +166,7 @@ if(flashStatus) { ...@@ -166,7 +166,7 @@ if(flashStatus) {
flashModeStatus = status flashModeStatus = status
}) })
if(flashModeStatus) { if(flashModeStatus) {
//设置自动闪光灯模式 // 设置自动闪光灯模式
cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => {
if (err) { if (err) {
console.error('Failed to set the flash mode ${err.message}'); console.error('Failed to set the flash mode ${err.message}');
...@@ -177,7 +177,7 @@ if(flashStatus) { ...@@ -177,7 +177,7 @@ if(flashStatus) {
} }
} }
//判断是否支持连续自动变焦模式 // 判断是否支持连续自动变焦模式
let focusModeStatus let focusModeStatus
cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err, status) => { cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err, status) => {
if (err) { if (err) {
...@@ -188,7 +188,7 @@ cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (e ...@@ -188,7 +188,7 @@ cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (e
focusModeStatus = status focusModeStatus = status
}) })
if(focusModeStatus) { if(focusModeStatus) {
//设置连续自动变焦模式 // 设置连续自动变焦模式
cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err) => { cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err) => {
if (err) { if (err) {
console.error('Failed to set the focus mode ${err.message}'); console.error('Failed to set the focus mode ${err.message}');
...@@ -198,7 +198,7 @@ if(focusModeStatus) { ...@@ -198,7 +198,7 @@ if(focusModeStatus) {
}) })
} }
//获取相机支持的可变焦距比范围 // 获取相机支持的可变焦距比范围
let zoomRatioRange let zoomRatioRange
cameraInput.getZoomRatioRange((err, range) => { cameraInput.getZoomRatioRange((err, range) => {
if (err) { if (err) {
...@@ -209,7 +209,7 @@ cameraInput.getZoomRatioRange((err, range) => { ...@@ -209,7 +209,7 @@ cameraInput.getZoomRatioRange((err, range) => {
zoomRatioRange = range zoomRatioRange = range
}) })
//设置可变焦距比 // 设置可变焦距比
cameraInput.setZoomRatio(zoomRatioRange[0], (err) => { cameraInput.setZoomRatio(zoomRatioRange[0], (err) => {
if (err) { if (err) {
console.error('Failed to set the zoom ratio value ${err.message}'); console.error('Failed to set the zoom ratio value ${err.message}');
...@@ -224,7 +224,7 @@ cameraInput.setZoomRatio(zoomRatioRange[0], (err) => { ...@@ -224,7 +224,7 @@ cameraInput.setZoomRatio(zoomRatioRange[0], (err) => {
##### 创建会话 ##### 创建会话
```js ```js
//创建Context对象 // 创建Context对象
let context = featureAbility.getContext() let context = featureAbility.getContext()
//创建会话 //创建会话
...@@ -238,7 +238,7 @@ await camera.createCaptureSession((context), (err, session) => { ...@@ -238,7 +238,7 @@ await camera.createCaptureSession((context), (err, session) => {
captureSession = session captureSession = session
}); });
//开始配置会话 // 开始配置会话
await captureSession.beginConfig((err) => { await captureSession.beginConfig((err) => {
if (err) { if (err) {
console.error('Failed to start the configuration. ${err.message}'); console.error('Failed to start the configuration. ${err.message}');
...@@ -247,7 +247,7 @@ await captureSession.beginConfig((err) => { ...@@ -247,7 +247,7 @@ await captureSession.beginConfig((err) => {
console.log('Callback invoked to indicate the begin config success.'); console.log('Callback invoked to indicate the begin config success.');
}); });
//向会话中添加相机输入流 // 向会话中添加相机输入流
await captureSession.addInput(cameraInput, (err) => { await captureSession.addInput(cameraInput, (err) => {
if (err) { if (err) {
console.error('Failed to add the CameraInput instance. ${err.message}'); console.error('Failed to add the CameraInput instance. ${err.message}');
...@@ -256,7 +256,7 @@ await captureSession.addInput(cameraInput, (err) => { ...@@ -256,7 +256,7 @@ await captureSession.addInput(cameraInput, (err) => {
console.log('Callback invoked to indicate that the CameraInput instance is added.'); console.log('Callback invoked to indicate that the CameraInput instance is added.');
}); });
//向会话中添加预览输入流 // 向会话中添加预览输入流
await captureSession.addOutput(previewOutput, (err) => { await captureSession.addOutput(previewOutput, (err) => {
if (err) { if (err) {
console.error('Failed to add the PreviewOutput instance ${err.message}'); console.error('Failed to add the PreviewOutput instance ${err.message}');
...@@ -265,7 +265,7 @@ await captureSession.addOutput(previewOutput, (err) => { ...@@ -265,7 +265,7 @@ await captureSession.addOutput(previewOutput, (err) => {
console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); console.log('Callback invoked to indicate that the PreviewOutput instance is added.');
}); });
//向会话中添加拍照输出流 // 向会话中添加拍照输出流
await captureSession.addOutput(photoOutput, (err) => { await captureSession.addOutput(photoOutput, (err) => {
if (err) { if (err) {
console.error('Failed to add the PhotoOutput instance ${err.message}'); console.error('Failed to add the PhotoOutput instance ${err.message}');
...@@ -274,7 +274,7 @@ await captureSession.addOutput(photoOutput, (err) => { ...@@ -274,7 +274,7 @@ await captureSession.addOutput(photoOutput, (err) => {
console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); console.log('Callback invoked to indicate that the PhotoOutput instance is added.');
}); });
//提交会话配置 // 提交会话配置
await captureSession.commitConfig((err) => { await captureSession.commitConfig((err) => {
if (err) { if (err) {
console.error('Failed to commit the configuration. ${err.message}'); console.error('Failed to commit the configuration. ${err.message}');
...@@ -283,7 +283,7 @@ await captureSession.commitConfig((err) => { ...@@ -283,7 +283,7 @@ await captureSession.commitConfig((err) => {
console.log('Callback invoked to indicate the commit config success.'); console.log('Callback invoked to indicate the commit config success.');
}); });
//启动会话 // 启动会话
await captureSession.start().then(() => { await captureSession.start().then(() => {
console.log('Promise returned to indicate the session start success.'); console.log('Promise returned to indicate the session start success.');
}) })
...@@ -292,7 +292,7 @@ await captureSession.start().then(() => { ...@@ -292,7 +292,7 @@ await captureSession.start().then(() => {
##### 切换会话 ##### 切换会话
```js ```js
//停止当前会话 // 停止当前会话
await captureSession.stop((err) => { await captureSession.stop((err) => {
if (err) { if (err) {
console.error('Failed to stop the session ${err.message}'); console.error('Failed to stop the session ${err.message}');
...@@ -301,7 +301,7 @@ await captureSession.stop((err) => { ...@@ -301,7 +301,7 @@ await captureSession.stop((err) => {
console.log('Callback invoked to indicate the session stop success.'); console.log('Callback invoked to indicate the session stop success.');
}); });
//开始配置会话 // 开始配置会话
await captureSession.beginConfig((err) => { await captureSession.beginConfig((err) => {
if (err) { if (err) {
console.error('Failed to start the configuration. ${err.message}'); console.error('Failed to start the configuration. ${err.message}');
...@@ -310,7 +310,7 @@ await captureSession.beginConfig((err) => { ...@@ -310,7 +310,7 @@ await captureSession.beginConfig((err) => {
console.log('Callback invoked to indicate the begin config success.'); console.log('Callback invoked to indicate the begin config success.');
}); });
//从会话中移除拍照输出流 // 从会话中移除拍照输出流
await captureSession.removeOutput(photoOutput, (err) => { await captureSession.removeOutput(photoOutput, (err) => {
if (err) { if (err) {
console.error('Failed to remove the PhotoOutput instance. ${err.message}'); console.error('Failed to remove the PhotoOutput instance. ${err.message}');
...@@ -319,7 +319,7 @@ await captureSession.removeOutput(photoOutput, (err) => { ...@@ -319,7 +319,7 @@ await captureSession.removeOutput(photoOutput, (err) => {
console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); console.log('Callback invoked to indicate that the PhotoOutput instance is removed.');
}); });
//向会话中添加录像输出流 // 向会话中添加录像输出流
await captureSession.addOutput(videoOutput, (err) => { await captureSession.addOutput(videoOutput, (err) => {
if (err) { if (err) {
console.error('Failed to add the VideoOutput instance ${err.message}'); console.error('Failed to add the VideoOutput instance ${err.message}');
...@@ -328,7 +328,7 @@ await captureSession.addOutput(videoOutput, (err) => { ...@@ -328,7 +328,7 @@ await captureSession.addOutput(videoOutput, (err) => {
console.log('Callback invoked to indicate that the VideoOutput instance is added.'); console.log('Callback invoked to indicate that the VideoOutput instance is added.');
}); });
//提交会话配置 // 提交会话配置
await captureSession.commitConfig((err) => { await captureSession.commitConfig((err) => {
if (err) { if (err) {
console.error('Failed to commit the configuration. ${err.message}'); console.error('Failed to commit the configuration. ${err.message}');
...@@ -337,7 +337,7 @@ await captureSession.commitConfig((err) => { ...@@ -337,7 +337,7 @@ await captureSession.commitConfig((err) => {
console.log('Callback invoked to indicate the commit config success.'); console.log('Callback invoked to indicate the commit config success.');
}); });
//启动会话 // 启动会话
await captureSession.start().then(() => { await captureSession.start().then(() => {
console.log('Promise returned to indicate the session start success.'); console.log('Promise returned to indicate the session start success.');
}) })
...@@ -347,10 +347,10 @@ await captureSession.start().then(() => { ...@@ -347,10 +347,10 @@ await captureSession.start().then(() => {
```js ```js
let settings = { let settings = {
quality: camera.QualityLevel.QUALITY_LEVEL_HIGH //设置图片质量高 quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高
rotation: camera.ImageRotation.ROTATION_0, //设置图片旋转角度0 rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0
} }
//使用当前拍照设置进行拍照 // 使用当前拍照设置进行拍照
photoOutput.capture(settings, (err) => { photoOutput.capture(settings, (err) => {
if (err) { if (err) {
console.error('Failed to capture the photo ${err.message}'); console.error('Failed to capture the photo ${err.message}');
...@@ -363,7 +363,7 @@ photoOutput.capture(settings, (err) => { ...@@ -363,7 +363,7 @@ photoOutput.capture(settings, (err) => {
#### 录像 #### 录像
```js ```js
//启动录像输出流 // 启动录像输出流
videoOutput.start((err) => { videoOutput.start((err) => {
if (err) { if (err) {
console.error('Failed to start the video output ${err.message}'); console.error('Failed to start the video output ${err.message}');
...@@ -372,17 +372,17 @@ videoOutput.start((err) => { ...@@ -372,17 +372,17 @@ videoOutput.start((err) => {
console.log('Callback invoked to indicate the video output start success.'); console.log('Callback invoked to indicate the video output start success.');
}); });
//开始录像 // 开始录像
await videoRecorder.start().then(() => { await videoRecorder.start().then(() => {
console.info('videoRecorder start success'); console.info('videoRecorder start success');
} }
//停止录像 // 停止录像
await videoRecorder.stop().then(() => { await videoRecorder.stop().then(() => {
console.info('stop success'); console.info('stop success');
} }
//停止录像输出流 // 停止录像输出流
await videoOutput.stop((err) => { await videoOutput.stop((err) => {
if (err) { if (err) {
console.error('Failed to stop the video output ${err.message}'); console.error('Failed to stop the video output ${err.message}');
...@@ -395,7 +395,7 @@ await videoOutput.stop((err) => { ...@@ -395,7 +395,7 @@ await videoOutput.stop((err) => {
#### 释放资源 #### 释放资源
```js ```js
//停止当前会话 // 停止当前会话
await captureSession.stop((err) => { await captureSession.stop((err) => {
if (err) { if (err) {
console.error('Failed to stop the session ${err.message}'); console.error('Failed to stop the session ${err.message}');
...@@ -403,7 +403,7 @@ await captureSession.stop((err) => { ...@@ -403,7 +403,7 @@ await captureSession.stop((err) => {
} }
console.log('Callback invoked to indicate the session stop success.'); console.log('Callback invoked to indicate the session stop success.');
}); });
//释放相机输入流 // 释放相机输入流
await cameraInput.release((err) => { await cameraInput.release((err) => {
if (err) { if (err) {
console.error('Failed to release the CameraInput instance ${err.message}'); console.error('Failed to release the CameraInput instance ${err.message}');
...@@ -411,7 +411,7 @@ await cameraInput.release((err) => { ...@@ -411,7 +411,7 @@ await cameraInput.release((err) => {
} }
console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); console.log('Callback invoked to indicate that the CameraInput instance is released successfully.');
}); });
//释放预览输出流 // 释放预览输出流
await previewOutput.release((err) => { await previewOutput.release((err) => {
if (err) { if (err) {
console.error('Failed to release the PreviewOutput instance ${err.message}'); console.error('Failed to release the PreviewOutput instance ${err.message}');
...@@ -419,7 +419,7 @@ await previewOutput.release((err) => { ...@@ -419,7 +419,7 @@ await previewOutput.release((err) => {
} }
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
}); });
//释放拍照输出流 // 释放拍照输出流
await photoOutput.release((err) => { await photoOutput.release((err) => {
if (err) { if (err) {
console.error('Failed to release the PhotoOutput instance ${err.message}'); console.error('Failed to release the PhotoOutput instance ${err.message}');
...@@ -427,7 +427,7 @@ await photoOutput.release((err) => { ...@@ -427,7 +427,7 @@ await photoOutput.release((err) => {
} }
console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.');
}); });
//释放录像输出流 // 释放录像输出流
await videoOutput.release((err) => { await videoOutput.release((err) => {
if (err) { if (err) {
console.error('Failed to release the VideoOutput instance ${err.message}'); console.error('Failed to release the VideoOutput instance ${err.message}');
...@@ -435,7 +435,7 @@ await videoOutput.release((err) => { ...@@ -435,7 +435,7 @@ await videoOutput.release((err) => {
} }
console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.');
}); });
//释放会话 // 释放会话
await captureSession.release((err) => { await captureSession.release((err) => {
if (err) { if (err) {
console.error('Failed to release the CaptureSession instance ${err.message}'); console.error('Failed to release the CaptureSession instance ${err.message}');
...@@ -449,24 +449,24 @@ await captureSession.release((err) => { ...@@ -449,24 +449,24 @@ await captureSession.release((err) => {
预览画面显示需要获取SurfaceId 预览画面显示需要获取SurfaceId
```js ```js
mXComponentController: XComponentController = new XComponentController //创建XComponentController mXComponentController: XComponentController = new XComponentController // 创建XComponentController
build() { build() {
Flex() { Flex() {
XComponent({ //创建XComponent XComponent({ // 创建XComponent
id: '', id: '',
type: 'surface', type: 'surface',
libraryname: '', libraryname: '',
controller: this.mXComponentController controller: this.mXComponentController
}) })
.onload(() => { //设置onload回调 .onload(() => { // 设置onload回调
//设置Surface宽高(1920*1080) // 设置Surface宽高(1920*1080)
this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080})
//获取Surface ID // 获取Surface ID
globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() globalThis.surfaceId = mXComponentController.getXComponentSurfaceId()
}) })
.width('1920px') //设置XComponent宽度 .width('1920px') // 设置XComponent宽度
.height('1080px') //设置XComponent高度 .height('1080px') // 设置XComponent高度
} }
} }
``` ```
\ No newline at end of file
...@@ -23,7 +23,7 @@ import image from '@ohos.multimedia.image' ...@@ -23,7 +23,7 @@ import image from '@ohos.multimedia.image'
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
//创建CameraManager对象 // 创建CameraManager对象
let cameraManager let cameraManager
await camera.getCameraManager(globalThis.Context, (err, manager) => { await camera.getCameraManager(globalThis.Context, (err, manager) => {
if (err) { if (err) {
...@@ -34,13 +34,13 @@ await camera.getCameraManager(globalThis.Context, (err, manager) => { ...@@ -34,13 +34,13 @@ await camera.getCameraManager(globalThis.Context, (err, manager) => {
cameraManager = manager cameraManager = manager
}) })
//注册回调函数监听相机状态变化,获取状态变化的相机信息 // 注册回调函数监听相机状态变化,获取状态变化的相机信息
cameraManager.on('cameraStatus', (cameraStatusInfo) => { cameraManager.on('cameraStatus', (cameraStatusInfo) => {
console.log('camera : ' + cameraStatusInfo.camera.cameraId); console.log('camera : ' + cameraStatusInfo.camera.cameraId);
console.log('status: ' + cameraStatusInfo.status); console.log('status: ' + cameraStatusInfo.status);
}) })
//获取相机列表 // 获取相机列表
let cameraArray let cameraArray
let remoteCamera let remoteCamera
await cameraManager.getCameras((err, cameras) => { await cameraManager.getCameras((err, cameras) => {
...@@ -53,16 +53,16 @@ await cameraManager.getCameras((err, cameras) => { ...@@ -53,16 +53,16 @@ await cameraManager.getCameras((err, cameras) => {
}) })
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) //获取相机ID console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // 获取相机ID
console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) //获取相机位置 console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // 获取相机位置
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) //获取相机类型 console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // 获取相机类型
console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) //获取相机连接类型 console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // 获取相机连接类型
if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) { if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) {
remoteCamera = cameraArray[cameraIndex].cameraId remoteCamera = cameraArray[cameraIndex].cameraId
} }
} }
//创建相机输入流 // 创建相机输入流
let cameraInput let cameraInput
await cameraManager.createCameraInput(remoteCamera).then((input) => { await cameraManager.createCameraInput(remoteCamera).then((input) => {
console.log('Promise returned with the CameraInput instance'); console.log('Promise returned with the CameraInput instance');
......
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
## 开发步骤 ## 开发步骤
详细API含义可参考:[媒体服务API文档VideoPlayer](../reference/apis/js-apis-media.md) 详细API含义可参考:[媒体服务API文档VideoPlayer](../reference/apis/js-apis-media.md#videoplayer8)
### 全流程场景 ### 全流程场景
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
## 开发步骤 ## 开发步骤
详细API含义可参考:[媒体服务API文档VideoRecorder](../reference/apis/js-apis-media.md) 详细API含义可参考:[媒体服务API文档VideoRecorder](../reference/apis/js-apis-media.md#videorecorder9)
### 全流程场景 ### 全流程场景
......
...@@ -65,7 +65,6 @@ app.json示例: ...@@ -65,7 +65,6 @@ app.json示例:
| entityType | 该标签标记该应用的类别,具体有 :游戏类(game),影音类(media)、社交通信类(communication)、新闻类(news)、出行类(travel)、工具类(utility)、购物类(shopping)、教育类(education)、少儿类(kids)、商务类(business)、拍摄类(photography)。 | 字符串 | 该标签可以缺省,缺省为unspecified。 | | entityType | 该标签标记该应用的类别,具体有 :游戏类(game),影音类(media)、社交通信类(communication)、新闻类(news)、出行类(travel)、工具类(utility)、购物类(shopping)、教育类(education)、少儿类(kids)、商务类(business)、拍摄类(photography)。 | 字符串 | 该标签可以缺省,缺省为unspecified。 |
| singleton | 标识该应用开启单例模式,仅支持系统应用配置,三方应用配置不生效。配置为true时,在多用户场景下,该应用仍然单实例运行,不会随用户切换而变动。采用布尔类型,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为false。 | | singleton | 标识该应用开启单例模式,仅支持系统应用配置,三方应用配置不生效。配置为true时,在多用户场景下,该应用仍然单实例运行,不会随用户切换而变动。采用布尔类型,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为false。 |
| removable | 标识应用是否可卸载,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 | | removable | 标识应用是否可卸载,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 |
| process | 标识应用进程名,标签值为字符串类型,最长为127个字节。如果app标签下配置了process,该应用的所有ability都运行在该进程中。 | 字符串 | 可缺省,缺省值为app标签下的bundleName。 |
| keepAlive | 标识应用是否始终保持运行状态,仅支持系统应用配置,三方应用配置不生效。标签值为布尔类型,如果为true,应用将始终保持为运行状态,并且在系统启动的时候会被系统启动起来,应用进程退出后,系统也会重新启动该应用进程。 | 布尔值 | 可缺省,缺省值为false。 | | keepAlive | 标识应用是否始终保持运行状态,仅支持系统应用配置,三方应用配置不生效。标签值为布尔类型,如果为true,应用将始终保持为运行状态,并且在系统启动的时候会被系统启动起来,应用进程退出后,系统也会重新启动该应用进程。 | 布尔值 | 可缺省,缺省值为false。 |
| userDataClearable | 标识是否允许应用清除用户数据,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 | | userDataClearable | 标识是否允许应用清除用户数据,仅支持系统应用配置,三方应用配置不生效,该字段从API8开始支持。 | 布尔值 | 可缺省,缺省值为true。 |
| accessible | 标识应用的安装目录是否是可访问的,仅支持系统应用配置,三方应用配置不生效。配置为true表示安装目录可以被三方应用访问,false表示不能被三方应用访问。 | 布尔值 | 可缺省,缺省值为false。 | | accessible | 标识应用的安装目录是否是可访问的,仅支持系统应用配置,三方应用配置不生效。配置为true表示安装目录可以被三方应用访问,false表示不能被三方应用访问。 | 布尔值 | 可缺省,缺省值为false。 |
...@@ -82,14 +81,13 @@ module.json5示例: ...@@ -82,14 +81,13 @@ module.json5示例:
"type": "entry|feature|har", "type": "entry|feature|har",
"srcEntrance" : "./MyAbilityStage.js", "srcEntrance" : "./MyAbilityStage.js",
"description" : "$string:description_application", "description" : "$string:description_application",
"process": "string",
"mainElement": "MainAbility", "mainElement": "MainAbility",
"deviceTypes": [ "deviceTypes": [
"tablet", "tablet",
"tv", "tv",
"wearable", "wearable",
"car", "car",
"router", "router"
], ],
"deliveryWithInstall": true, "deliveryWithInstall": true,
"installationFree": false, "installationFree": false,
...@@ -176,7 +174,7 @@ hap包的配置信息,该标签下的配置只对当前hap包生效。 ...@@ -176,7 +174,7 @@ hap包的配置信息,该标签下的配置只对当前hap包生效。
| type | 该标签标识当前hap的类型。类型有三种,分别是entry、feature和har。 | 字符串 | 该标签不可缺省。 | | type | 该标签标识当前hap的类型。类型有三种,分别是entry、feature和har。 | 字符串 | 该标签不可缺省。 |
| srcEntrance | 该标签标识hap所对应的入口js代码路径,标签值为字符串(最长为127字节)。 | 字符串 | 该标签可缺省。 | | srcEntrance | 该标签标识hap所对应的入口js代码路径,标签值为字符串(最长为127字节)。 | 字符串 | 该标签可缺省。 |
| description | 该标签标识hap包的描述信息,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 | | description | 该标签标识hap包的描述信息,标签值是是字符串类型或对描述内容的资源索引,以支持多语言。 | 字符串 | 该标签可缺省,缺省值为空。 |
| process | 该标签标识hap的进程名,标签值为字符串类型(最长为31个字节)。如果在hap标签下配置了process,该应用的所有ability都运行在该进程中。 | 字符串 | 可缺省,缺省为app标签下的bundleName。 | | process | 该标签标识hap的进程名,标签值为字符串类型(最长为31个字节)。如果在hap标签下配置了process,该应用的所有ability都运行在该进程中。该标签只支持系统应用配置。 | 字符串 | 可缺省,缺省为app标签下的bundleName。 |
| mainElement | 该标签标识hap的入口ability名称或者extension名称。只有配置为mainElement的ability或者extension才允许在服务中心露出。创建OpenHarmony原子化服务时,该标签不可缺省。 | 字符串 | OpenHarmony应用下,该标签可缺省。 | | mainElement | 该标签标识hap的入口ability名称或者extension名称。只有配置为mainElement的ability或者extension才允许在服务中心露出。创建OpenHarmony原子化服务时,该标签不可缺省。 | 字符串 | OpenHarmony应用下,该标签可缺省。 |
| deviceTypes | 该标签标识hap可以运行在哪类设备上,标签值采用字符串数组的表示,系统预定义的设备类型见表4。<br />与syscap不同的是,deviceTypes是以设备类型为粒度,而syscap是以设备能力(例如蓝牙、wifi)为粒度。 | 字符串数组 | 该标签不可缺省,可以为空值。 | | deviceTypes | 该标签标识hap可以运行在哪类设备上,标签值采用字符串数组的表示,系统预定义的设备类型见表4。<br />与syscap不同的是,deviceTypes是以设备类型为粒度,而syscap是以设备能力(例如蓝牙、wifi)为粒度。 | 字符串数组 | 该标签不可缺省,可以为空值。 |
| deliveryWithInstall | 该标签标识当前hap是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | 布尔值 | 该标签不可缺省。 | | deliveryWithInstall | 该标签标识当前hap是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | 布尔值 | 该标签不可缺省。 |
...@@ -403,10 +401,10 @@ skills示例 ...@@ -403,10 +401,10 @@ skills示例
"pathRegex":"/query/.*", "pathRegex":"/query/.*",
"path":"path", "path":"path",
"type": "text/*" "type": "text/*"
}, }
] ]
} }
], ]
} }
], ],
"extensionAbilities": [ "extensionAbilities": [
...@@ -426,12 +424,12 @@ skills示例 ...@@ -426,12 +424,12 @@ skills示例
"pathRegex":"/query/.*", "pathRegex":"/query/.*",
"path":"path", "path":"path",
"type": "text/*" "type": "text/*"
}, }
] ]
} }
], ]
} }
], ]
} }
``` ```
......
...@@ -279,7 +279,7 @@ ...@@ -279,7 +279,7 @@
1. 将搭载OpenHarmony标准系统的开发板与电脑连接。 1. 将搭载OpenHarmony标准系统的开发板与电脑连接。
2. 点击**File**&gt; **Project Structure...** &gt; **Project**&gt;**SigningConfigs**界面勾选“**Automatically generate signaure**”,等待自动签名完成即可,点击“**OK**”。如下图所示: 2. 点击**File**&gt; **Project Structure...** &gt; **Project**&gt;**SigningConfigs**界面勾选“**Automatically generate signature**”,等待自动签名完成即可,点击“**OK**”。如下图所示:
![06](figures/06.png) ![06](figures/06.png)
......
...@@ -26,10 +26,12 @@ OpenHarmony中提供的接口,部分是仅供OEM厂商使用的system api, ...@@ -26,10 +26,12 @@ OpenHarmony中提供的接口,部分是仅供OEM厂商使用的system api,
- 如果某个模块的接口均为system api,会在文档开头说明:该模块接口为系统接口。 - 如果某个模块的接口均为system api,会在文档开头说明:该模块接口为系统接口。
- 如果某个接口为system api,会在具体的接口描述中说明:此接口为系统接口。 - 如果某个接口为system api,会在具体的接口描述中说明:此接口为系统接口。
普通应用即应用APL等级为normal的应用。默认情况下,应用的等级都为normal应用 普通应用即应用APL等级为normal的应用。应用等级默认为normal
APL等级的详细说明及如何将应用的APL等级声明为normal以上,请参考[访问控制开发概述-应用APL等级说明](../../security/accesstoken-overview.md#应用apl等级说明) APL等级的详细说明及如何将应用的APL等级声明为normal以上,请参考[访问控制开发概述-应用APL等级说明](../../security/accesstoken-overview.md#应用apl等级说明)
随DevEco下载的SDK为public-SDK,不包括系统接口。如需使用系统接口,需要将SDK替换为full-SDK,具体参考[full-SDK替换指南](../../quick-start/full-sdk-switch-guide.md)
## 权限说明 ## 权限说明
默认情况下,应用只能访问有限的系统资源。但某些情况下,应用为了扩展功能的诉求,需要访问额外的系统或其他应用的数据(包括用户个人数据)、功能。具体可参考[访问控制开发概述](../../security/accesstoken-overview.md) 默认情况下,应用只能访问有限的系统资源。但某些情况下,应用为了扩展功能的诉求,需要访问额外的系统或其他应用的数据(包括用户个人数据)、功能。具体可参考[访问控制开发概述](../../security/accesstoken-overview.md)
......
...@@ -158,7 +158,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -158,7 +158,7 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 | | 名称 | 类型 | 必填 | 描述 |
| ----------- | ------ | ---- | ------------------------------------------------------------ | | ----------- | ------ | ---- | ------------------------------------------------------------ |
| bundleName | string | 是 | 要查询的包名。 | | bundleName | string | 是 | 要查询的包名。 |
| bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)信息相关flag。 | | bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)应用信息相关flag。 |
| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:** **返回值:**
...@@ -196,7 +196,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -196,7 +196,7 @@ SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 必填 | 描述 | | 名称 | 类型 | 必填 | 描述 |
| ----------- | ------ | ---- | ------------------------------------------------------------ | | ----------- | ------ | ---- | ------------------------------------------------------------ |
| bundleName | string | 是 | 要查询的包名。 | | bundleName | string | 是 | 要查询的包名。 |
| bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)信息相关flag。 | | bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)应用信息相关flag。 |
**返回值:** **返回值:**
...@@ -448,7 +448,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { ...@@ -448,7 +448,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => {
getBundleInfoSync(bundleName: string, bundleFlags: number, options: BundleOptions): BundleInfo; getBundleInfoSync(bundleName: string, bundleFlags: number, options: BundleOptions): BundleInfo;
以同步方法根据给定的包名获取ApplicationInfo,返回BundleInfo对象。 以同步方法根据给定的包名获取BundleInfo,返回BundleInfo对象。
**需要权限:** **需要权限:**
...@@ -488,7 +488,7 @@ console.info('Operation successful. Name:' + bundleInfo.name); ...@@ -488,7 +488,7 @@ console.info('Operation successful. Name:' + bundleInfo.name);
getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo; getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo;
以同步方法根据给定的包名获取ApplicationInfo,返回BundleInfo对象。 以同步方法根据给定的包名获取BundleInfo,返回BundleInfo对象。
**需要权限:** **需要权限:**
...@@ -2619,7 +2619,7 @@ ExtensionAbility的类型 ...@@ -2619,7 +2619,7 @@ ExtensionAbility的类型
此项仅供内部系统使用 此项仅供内部系统使用
**系统API:**此接口为系统接口,三方应用不支持调用 **系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
...@@ -2628,3 +2628,154 @@ ExtensionAbility的类型 ...@@ -2628,3 +2628,154 @@ ExtensionAbility的类型
| NOT_UPGRADE<sup>9+</sup> | 0 | 模块无需升级 | | NOT_UPGRADE<sup>9+</sup> | 0 | 模块无需升级 |
| SINGLE_UPGRADE<sup>9+</sup> | 1 | 单个模块需要升级 | | SINGLE_UPGRADE<sup>9+</sup> | 1 | 单个模块需要升级 |
| RELATION_UPGRADE<sup>9+</sup> | 2 | 关系模块需要升级 | | RELATION_UPGRADE<sup>9+</sup> | 2 | 关系模块需要升级 |
## BundlePackFlag
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 值 | 说明 |
| ------------------ | ---------- | -------------------------------- |
| GET_PACK_INFO_ALL | 0x00000000 | 获取应用包pack.info的所有信息 |
| GET_PACKAGES | 0x00000001 | 获取应用包pack.info的package信息 |
| GET_BUNDLE_SUMMARY | 0x00000002 | 获取应用包pack.info的bundle摘要 |
| GET_MODULE_SUMMARY | 0x00000004 | 获取应用包pack.info的module摘要 |
## BundlePackInfo
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------------------- | ---- | ---- | --------------------------- |
| packages | Array<PackageConfig> | 是 | 否 | 获取pack.info的包信息 |
| summary | PackageSummary | 是 | 否 | 获取pack.info中的包摘要信息 |
## PackageConfig
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------- | ------------- | ---- | ---- | ------------------------------------------------------------ |
| deviceType | Array<string> | 是 | 否 | 包支持的设备类型 |
| name | string | 是 | 否 | 包的名称 |
| moduleType | string | 是 | 否 | 包的module类型 |
| deliveryWithInstall | boolean | 是 | 否 | 是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 |
## PackageSummary
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------- | ----------------------- | ---- | ---- | ------------------ |
| app | BundleConfigInfo | 是 | 否 | 包的配置信息 |
| modules | Array<ModuleConfigInfo> | 是 | 否 | 包的module配置信息 |
## BundleConfigInfo
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ---------- | ------------------- | ---- | ---- | ---------------------------------- |
| bundleName | string | 是 | 否 | 应用的包名,用于标识应用的唯一性。 |
| version | [Version](#version) | 是 | 否 | 包的版本 |
## ModuleConfigInfo
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------ | ------------------------- | ---- | ---- | -------------------------------- |
| apiVersion | ApiVersion | 是 | 否 | module的api版本 |
| deviceType | Array<string> | 是 | 否 | module的设备类型 |
| distro | ModuleDistroInfo | 是 | 否 | module发行版信息 |
| abilities | Array<ModuleAbilityInfo> | 是 | 否 | module的元能力信息 |
| extensionAbilities | Array<ExtensionAbilities> | 是 | 否 | 描述extensionAbilities的配置信息 |
## ModuleDistroInfo
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ |
| mainAbility | string | 是 | 否 | 主要能力的名称 |
| deliveryWithInstall | boolean | 是 | 否 | 是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 |
| installationFree | boolean | 是 | 否 | 表示当前HAP是否支持免安装特性。true表示支持免安装特性,且符合免安装约束,false表示不支持免安装特性。 |
| moduleName | string | 是 | 否 | module名称 |
| moduleType | string | 是 | 否 | module类型 |
## ModuleAbilityInfo
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ |
| name | string | 是 | 否 | 表示当前ability的逻辑名,该名称在整个应用要唯一。 |
| label | string | 是 | 否 | 表示ability对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。 |
| visible | boolean | 是 | 否 | 表示ability是否可以被其它应用调用,true表示可以被其它应用调用,false表示不可以被其它应用调用。 |
| forms | Array<AbilityFormInfo> | 是 | 否 | 卡片信息 |
## ExtensionAbilities
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ----- | ---------------------- | ---- | ---- | ------------------------------------------------------------ |
| forms | Array<AbilityFormInfo> | 是 | 否 | 表示form卡片的规格,form卡片是可以嵌入桌面上并接收定时更新的应用简要视图。 |
## AbilityFormInfo
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------- | ------------- | ---- | ---- | ------------------------------------------------------------ |
| name | string | 是 | 否 | 表示forms的名称 |
| type | string | 是 | 否 | 表示forms的类型 |
| updateEnabled | boolean | 是 | 否 | 表示该卡片是否支持定时刷新,true表示卡片支持定时刷新,false表示不支持。 |
| scheduledUpdateTime | string | 是 | 否 | 表示卡片定点刷新的时间,采用24小时计数,精确到分钟。 |
| updateDuration | number | 是 | 否 | 表示卡片定时刷新的更新频率,单位为30分钟,取值为30的倍数值。卡片的最高频率为每30分钟刷新一次,和定点刷新二选一,二者都配置的情况下,定时优先。 |
| supportDimensions | Array<number> | 是 | 否 | 表示卡片外观规格,取值为“1\*2”,“2\*2”,“2\*4”,“4\*4”,定义卡片时至少要指定一个卡片规格。 |
| defaultDimension | number | 是 | 否 | 表示卡片默认外观规格,取值必须在supportDimensions配置的列表中。 |
## ApiVersion
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------- | ------ | ---- | ---- | ------------------ |
| releaseType | string | 是 | 否 | 版本的最小兼容代码 |
| compatible | number | 是 | 否 | 版本的名称 |
| target | numbe | 是 | 否 | 目标版本号 |
## Version
**系统API:** 此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
| minCompatibleVersionCode | number | 是 | 否 | 能够兼容的最低历史版本号,用于跨设备兼容性判断。该值为32位整型数值,非负整数。 |
| name | string | 是 | 否 | 标识版本号的文字描述,用于向用户展示。 |
| code | number | 是 | 否 | 标识应用的版本号,值为32位非负整数。此数字仅用于确定某个版本是否比另一个版本更新,数值越大表示版本越高。 |
...@@ -631,7 +631,7 @@ createPreviewOutput(profile: Profile, surfaceId: string): Promise<PreviewOutput\ ...@@ -631,7 +631,7 @@ createPreviewOutput(profile: Profile, surfaceId: string): Promise<PreviewOutput\
**示例:** **示例:**
```js ```js
cameraManager.createPreviewOutput(profile, survaceId).then((previewoutput) => { cameraManager.createPreviewOutput(profile, surfaceId).then((previewoutput) => {
console.log('Promise returned with previewOutput created.'); console.log('Promise returned with previewOutput created.');
}) })
``` ```
...@@ -2262,7 +2262,7 @@ cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(er ...@@ -2262,7 +2262,7 @@ cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(er
console.log(`Failed to check exposure mode supported ${err.message}`); console.log(`Failed to check exposure mode supported ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of isExposureModeSupported'); console.log('Callback returned with the successful execution of isExposureModeSupported');
}) })
``` ```
...@@ -2365,7 +2365,7 @@ cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { ...@@ -2365,7 +2365,7 @@ cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => {
console.log(`Failed to set the exposure mode ${err.message}`); console.log(`Failed to set the exposure mode ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setExposureMode'); console.log('Callback returned with the successful execution of setExposureMode');
}) })
``` ```
...@@ -2464,7 +2464,7 @@ cameraInput.setMeteringPoint(Point1,(err) => { ...@@ -2464,7 +2464,7 @@ cameraInput.setMeteringPoint(Point1,(err) => {
console.log(`Failed to set the exposure point ${err.message}`); console.log(`Failed to set the exposure point ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setMeteringPoint'); console.log('Callback returned with the successful execution of setMeteringPoint');
}) })
``` ```
...@@ -2571,7 +2571,7 @@ cameraInput.setExposureBias(-4,(err) => { ...@@ -2571,7 +2571,7 @@ cameraInput.setExposureBias(-4,(err) => {
console.log(`Failed to set the exposure bias ${err.message}`); console.log(`Failed to set the exposure bias ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setExposureBias'); console.log('Callback returned with the successful execution of setExposureBias');
}) })
``` ```
...@@ -3545,7 +3545,7 @@ previewOutput.stop((err) => { ...@@ -3545,7 +3545,7 @@ previewOutput.stop((err) => {
console.error(`Failed to stop the previewOutput. ${err.message}`); console.error(`Failed to stop the previewOutput. ${err.message}`);
return; return;
} }
console.log('Callback returned with previewOutput stoped.'); console.log('Callback returned with previewOutput stopped.');
}) })
``` ```
...@@ -3567,7 +3567,7 @@ stop(): Promise<void\> ...@@ -3567,7 +3567,7 @@ stop(): Promise<void\>
```js ```js
previewOutput.stop().then(() => { previewOutput.stop().then(() => {
console.log('Callback returned with previewOutput stoped.'); console.log('Callback returned with previewOutput stopped.');
}) })
``` ```
...@@ -4476,7 +4476,7 @@ metadataOutput.stop((err) => { ...@@ -4476,7 +4476,7 @@ metadataOutput.stop((err) => {
console.error(`Failed to stop the metadataOutput. ${err.message}`); console.error(`Failed to stop the metadataOutput. ${err.message}`);
return; return;
} }
console.log('Callback returned with metadataOutput stoped.'); console.log('Callback returned with metadataOutput stopped.');
}) })
``` ```
...@@ -4498,7 +4498,7 @@ stop(): Promise<void\> ...@@ -4498,7 +4498,7 @@ stop(): Promise<void\>
```js ```js
metadataOutput.stop().then(() => { metadataOutput.stop().then(() => {
console.log('Callback returned with metadataOutput stoped.'); console.log('Callback returned with metadataOutput stopped.');
}) })
``` ```
......
...@@ -46,7 +46,7 @@ constructor是URI的构造函数。 ...@@ -46,7 +46,7 @@ constructor是URI的构造函数。
**示例:** **示例:**
```js ```js
var mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; let mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment';
new uri.URI(mm); // Output 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; new uri.URI(mm); // Output 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment';
``` ```
```js ```js
......
...@@ -159,4 +159,5 @@ ...@@ -159,4 +159,5 @@
- [时间选择弹窗](ts-methods-timepicker-dialog.md) - [时间选择弹窗](ts-methods-timepicker-dialog.md)
- [文本选择弹窗](ts-methods-textpicker-dialog.md) - [文本选择弹窗](ts-methods-textpicker-dialog.md)
- [菜单](ts-methods-menu.md) - [菜单](ts-methods-menu.md)
- [文档中涉及到的内置枚举值](ts-appendix-enums.md) - [枚举说明](ts-appendix-enums.md)
- [类型说明](ts-types.md)
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册