提交 e44e193a 编写于 作者: L lanyi 提交者: Gitee

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

......@@ -20,24 +20,23 @@
- Development
- [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md)
- Basic Feature Development
- [Common Event and Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management](background-task-management/Readme-EN.md)
- [Work Scheduler](work-scheduler/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
- [Common Event and Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md)
- [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management](background-task-management/Readme-EN.md)
- [Work Scheduler](work-scheduler/Readme-EN.md)
- [Device Management](device/Readme-EN.md)
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md)
- [OpenHarmony IDL Specifications and User Guide](IDL/idl-guidelines.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
- Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials
......
......@@ -12,8 +12,8 @@ The APIs provided by the test framework can be used only in the test HAP. They t
The test framework can be started in either of the following ways:
- Method 1: Run the <idp:inline class="- topic/inline " val="code" displayname="code" id="code779717408187" tempcmdid="code779717408187">aa test</idp:inline> command.
- Method 2: Use the IDE.
- Method 1: Run the `aa test` command.
- Method 2: Use DevEco Studio.
### Running aa test
......@@ -37,16 +37,16 @@ aa test -b BundleName -m com.example.myapplicationfaets -s unittest OpenHarmonyT
| -s unittest | Yes | Name of the **TestRunner** to be used. The TestRunner name must be the same as the file name. |
| -w | No | Timeout interval of a test case, in seconds. If this parameter is not specified or is set to a value less than or equal to **0**, the test framework exits only after **finishTest** is invoked.|
| -s \<key>\<value> | No | **-s** can be followed by any key-value pair obtained through **AbilityDelegatorArgs.parameters**. For example, in **-s classname myTest**, **-s classname** is the key and **myTest** is the value.|
| -D | No | Debug mode for starting the tested application. |
| -h | No | Help information. |
| -D | No | Debug mode for starting the tested application.|
| -h | No | Help information.|
### Using the IDE
### Using DevEco Studio
For details about how to use the IDE to start the test framework, see [IDE Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508).
For details about how to use DevEco Studio to start the test framework, see [OpenHarmony Test Framework](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508).
## Introduction to TestRunner
**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, the IDE initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md).
**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and overwrite the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md).
## Introduction to AbilityDelegatorRegistry
......@@ -136,6 +136,7 @@ abilityDelegator.startAbility(want, (err, data) => {
### Running a Shell Command
**AbilityDelegator** provides APIs to run shell commands in the test environment.
**Example**
```javascript
......@@ -150,6 +151,7 @@ abilityDelegator.executeShellCommand(cmd, (err, data) => {
### Printing Log Information
**AbilityDelegator** provides APIs for printing log information. You can call any API in the test code to print process logs to the unit test console.
**Example**
```javascript
......@@ -165,6 +167,7 @@ abilityDelegator.print(msg, (err) => {
### Finishing the Test and Printing Log Information
**AbilityDelegator** provides the APIs for actively finishing the test. You can call any API in test code to finish the test and print logs to the unit test console.
**Example**
```javascript
......
......@@ -3,20 +3,12 @@
## Widget Overview
A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
Basic concepts:
- Widget provider
The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget.
- Widget host
The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager
The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users.
- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
......@@ -30,7 +22,7 @@ The widget provider controls the widget content to display, component layout, an
Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations:
- Develop the lifecycle callbacks in **LifecycleForm**.
- Create a **FormBindingData** object.
- Create a **FormBindingData** instance.
- Update a widget through **FormProvider**.
- Develop the widget UI page.
......@@ -46,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**.
| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. |
| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. |
| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. |
| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a specified widget. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. |
For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md).
......@@ -81,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
export default {
onCreate(want) {
console.log('FormAbility onCreate');
// Persistently store widget information for subsequent use, such as widget instance retrieval and update.
// Persistently store widget information for subsequent use, such as during widget instance retrieval or update.
let obj = {
"title": "titleOnCreate",
"detail": "detailOnCreate"
......@@ -94,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
console.log('FormAbility onCastToNormal');
},
onUpdate(formId) {
// To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update.
// To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
console.log('FormAbility onUpdate');
let obj = {
"title": "titleOnUpdate",
......@@ -124,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
}
```
### Configuring config.json for the Form Ability
### Configuring the Widget Configuration File
Configure the **config.json** file for the **Form** ability.
Configure the **config.json** file for the widget.
- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows:
- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows:
| Field| Description | Data Type| Default |
| -------- | ------------------------------------------------------------ | -------- | ------------------------ |
......@@ -161,12 +153,12 @@ Configure the **config.json** file for the **Form** ability.
| isDefault | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean | No |
| type | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget. | String | No |
| colorMode | Color mode of the widget. Available values are as follows:<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)|
| supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>1 * 2: indicates a grid with one row and two columns.<br>2 * 2: indicates a grid with two rows and two columns.<br>2 * 4: indicates a grid with two rows and four columns.<br>4 * 4: indicates a grid with four rows and four columns.| String array| No |
| supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No |
| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No |
| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No |
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) |
| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) |
| formConfigAbility | Indicates the link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) |
| formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) |
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) |
| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No |
| metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) |
......@@ -203,7 +195,7 @@ Configure the **config.json** file for the **Form** ability.
```
### Widget Data Persistence
### Persistently Store Widget Data
Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget.
......@@ -215,6 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information
let formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget information for subsequent use, such as widget instance retrieval and update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples".
storeFormInfo(formId, formName, tempFlag, want);
let obj = {
......@@ -230,26 +223,28 @@ You should override **onDestroy** to delete widget data.
```javascript
onDestroy(formId) {
// Delete widget data.
deleteFormInfo(formId);
console.log('FormAbility onDestroy');
// You need to implement the code for deleting the persistent widget instance.
// The deleteFormInfo API is not implemented here. For details, see "Widget Host" provided in "Samples".
deleteFormInfo(formId);
}
```
For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md).
Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one.
- Normal widget: a widget that will be persistently used by the widget host
Normal widget: a widget that will be persistently used by the widget host
Temporary widget: a widget that is temporarily used by the widget host
- Temporary widget: a widget that is temporarily used by the widget host
Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets.
### Developing the Widget UI Page
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.
- HML:
......@@ -331,10 +326,8 @@ Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png)
## Development Example
The following sample is provided to help you better understand how to develop a widget on the FA model:
[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
## Samples
This sample provides a widget. Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage.
The following samples are provided to help you better understand how to develop a widget on the FA model:
- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher)
......@@ -83,7 +83,7 @@ export default class MySequenceable {
```
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 **CalleeSortMethod** 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 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:
```ts
const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg'
......@@ -148,7 +148,7 @@ async onButtonGetCaller() {
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 sample code snippet is as follows:
```ts
let TAG = '[MainAbility] '
var caller = undefined
......@@ -172,7 +172,7 @@ context.startAbilityByCall({
console.error(TAG + '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 sample code snippet is as follows:
```ts
import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass;
......@@ -190,7 +190,7 @@ function getRemoteDeviceId() {
}
}
```
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, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows:
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
......@@ -215,7 +215,7 @@ async onButtonCall() {
}
```
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 and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows:
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = ''
......
......@@ -165,14 +165,4 @@ The following example shows how to implement a distributed data object synchroni
```js
local_object.setSessionId("");
```
## Samples
The following example is provided for you to better understand the development of distributed data objects:
- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad)
When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network.
```
\ No newline at end of file
......@@ -178,7 +178,3 @@ The following uses a single KV store as an example to describe the development p
}
});
```
## Samples
The following samples are provided to help you better understand the distributed data development:
- [`KvStore`: Distributed Data Management (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [Distributed Data Service](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
......@@ -8,7 +8,7 @@ In Host mode, you can obtain the list of connected devices, enable or disable th
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md).
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md).
**Table 1** Open USB APIs
......
# Audio Capture Development
---
## ***Note***:
1. This document applies to JavaScript.
---
## **Summary**
This guide will show how a JS application can use AudioCapturer to record the audio.
Applications can use the APIs provided in this document to record raw audio files.
## **AudioCapturer Framework**
The AudioCapturer interface is one of the most important components of the audio framework.
### **Audio Capturing:**
The AudioCapturer framework provides APIs for capturing raw audio files.
## **Usage**
Here's an example of how to use AudioCapturer to capture a raw audio file.
1. Use **createAudioCapturer()** to create an AudioCapturer instance. Capturer parameters can be set in **audioCapturerOptions**.\
This instance can be used to record, control, and obtain the recording status, as well as to register a callback for notifications.
```
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 1
}
var audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions);
var state = audioRenderer.state;
```
## When to Use
You can use the APIs provided by **AudioCapturer** to record raw audio files.
### State Check
During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior.
For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md).
**Figure 1** Audio capturer state
![](figures/audio-capturer-state.png)
## How to Develop
1. Use **createAudioCapturer()** to create an **AudioCapturer** instance.
Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification.
2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API.
If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event.
There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details.
```js
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 1
}
var audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions);
var state = audioRenderer.state;
```
2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes.
If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
```js
audioCapturer.on('stateChange',(state) => {
console.info('AudioCapturerLog: Changed State to : ' + state)
switch (state) {
case audio.AudioState.STATE_PREPARED:
console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------');
console.info('Audio State is : Prepared');
break;
case audio.AudioState.STATE_RUNNING:
console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------');
console.info('Audio State is : Running');
break;
case audio.AudioState.STATE_STOPPED:
console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------');
console.info('Audio State is : stopped');
break;
case audio.AudioState.STATE_RELEASED:
console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------');
console.info('Audio State is : released');
break;
default:
console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------');
console.info('Audio State is : invalid');
break;
}
case audio.AudioState.STATE_PREPARED:
console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------');
console.info('Audio State is : Prepared');
break;
case audio.AudioState.STATE_RUNNING:
console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------');
console.info('Audio State is : Running');
break;
case audio.AudioState.STATE_STOPPED:
console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------');
console.info('Audio State is : stopped');
break;
case audio.AudioState.STATE_RELEASED:
console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------');
console.info('Audio State is : released');
break;
default:
console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------');
console.info('Audio State is : invalid');
break;
}
});
```
3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\
The capturer state will be STATE_RUNNING once the start is complete. The application can then begin reading buffers.
```
await audioCapturer.start();
if (audioCapturer.state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started');
} else {
console.info('AudioRecLog: Capturer start failed');
}
3. Use **start()** to start audio recording.
```
The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers.
4. Obtain the minimum buffer size to read using the **getBufferSize()** API.
```js
await audioCapturer.start();
if (audioCapturer.state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started');
} else {
console.info('AudioRecLog: Capturer start failed');
}
```
var bufferSize = await audioCapturer.getBufferSize();
console.info('AudioRecLog: buffer size: ' + bufferSize);
```
4. Use **getBufferSize()** to obtain the minimum buffer size to read.
5. Read the captured audio data and convert it to a byte stream. Call the **read()** API repeatedly to read the data
until the application wants to stop the recording. The following example shows how to write recorded data into a file.
```js
var bufferSize = await audioCapturer.getBufferSize();
console.info('AudioRecLog: buffer size: ' + bufferSize);
```
import fileio from '@ohos.fileio';
const path = '/data/data/.pulse_dir/capture_js.wav';
let fd = fileio.openSync(path, 0o102, 0o777);
if (fd !== null) {
console.info('AudioRecLog: file fd created');
}
else{
console.info('AudioRecLog: file fd create : FAILED');
return;
}
fd = fileio.openSync(path, 0o2002, 0o666);
if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode');
}
var numBuffersToCapture = 150;
while (numBuffersToCapture) {
var buffer = await audioCapturer.read(bufferSize, true);
if (typeof(buffer) == undefined) {
console.info('read buffer failed');
} else {
var number = fileio.writeSync(fd, buffer);
console.info('AudioRecLog: data written: ' + number);
}
numBuffersToCapture--;
}
```
6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording.
```
await audioCapturer.stop();
if (audioCapturer.state == audio.AudioState.STATE_STOPPED) {
console.info('AudioRecLog: Capturer stopped');
} else {
console.info('AudioRecLog: Capturer stop failed');
}
5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording.
The following example shows how to write recorded data into a file.
```js
import fileio from '@ohos.fileio';
const path = '/data/data/.pulse_dir/capture_js.wav';
let fd = fileio.openSync(path, 0o102, 0o777);
if (fd !== null) {
console.info('AudioRecLog: file fd created');
}
else{
console.info('AudioRecLog: file fd create : FAILED');
return;
}
fd = fileio.openSync(path, 0o2002, 0o666);
if (fd !== null) {
console.info('AudioRecLog: file fd opened in append mode');
}
var numBuffersToCapture = 150;
while (numBuffersToCapture) {
var buffer = await audioCapturer.read(bufferSize, true);
if (typeof(buffer) == undefined) {
console.info('read buffer failed');
} else {
var number = fileio.writeSync(fd, buffer);
console.info('AudioRecLog: data written: ' + number);
}
numBuffersToCapture--;
}
```
7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources.
6. Once the recording is complete, call **stop()** to stop the recording.
```
await audioCapturer.release();
if (audioCapturer.state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released');
} else {
console.info('AudioRecLog: Capturer release failed');
}
await audioCapturer.stop();
if (audioCapturer.state == audio.AudioState.STATE_STOPPED) {
console.info('AudioRecLog: Capturer stopped');
} else {
console.info('AudioRecLog: Capturer stop failed');
}
```
## **Importance of State Check**
Application developers should keep in mind that an AudioCapturer is state-based.
That is, the AudioCapturer has an internal state that the application must always check when calling recorder control APIs, because some operations are only acceptable while the capturer is in a given state.\
The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state.
7. After the task is complete, call **release()** to release related resources.
## **Other APIs**
See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**.
```js
await audioCapturer.release();
if (audioCapturer.state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released');
} else {
console.info('AudioRecLog: Capturer release failed');
}
```
# Native APIs
- [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md)
- [Raw File Development](rawfile-guidelines.md)
# Drawing Development
## When to Use
The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development:
* Drawing 2D graphics
* Drawing and painting text
## Available APIs
| API| Description|
| -------- | -------- |
| OH_Drawing_BitmapCreate (void) | Creates a bitmap object.|
| OH_Drawing_BitmapBuild (OH_Drawing_Bitmap *, const uint32_t width, const uint32_t height, const OH_Drawing_BitmapFormat *) | Initializes the width and height of a bitmap object and sets the pixel format for the bitmap.|
| OH_Drawing_CanvasCreate (void) | Creates a canvas object.|
| OH_Drawing_CanvasBind (OH_Drawing_Canvas *, OH_Drawing_Bitmap *) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap (this process is called CPU rendering).|
| OH_Drawing_CanvasAttachBrush (OH_Drawing_Canvas *, const OH_Drawing_Brush *) | Attaches a brush to a canvas so that the canvas will use the style and color of the brush to fill in a shape.|
| OH_Drawing_CanvasAttachPen (OH_Drawing_Canvas *, const OH_Drawing_Pen *) | Attaches a pen to a canvas so that the canvas will use the style and color of the pen to outline a shape.|
| OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.|
| OH_Drawing_PathCreate (void) | Creates a path object.|
| OH_Drawing_PathMoveTo (OH_Drawing_Path *, float x, float y) | Sets the start point of a path.|
| OH_Drawing_PathLineTo (OH_Drawing_Path *, float x, float y) | Draws a line segment from the last point of a path to the target point. |
| OH_Drawing_PathClose (OH_Drawing_Path *) | Closes a path. A line segment from the start point to the last point of the path is added.|
| OH_Drawing_PenCreate (void) | Creates a pen object.|
| OH_Drawing_PenSetAntiAlias (OH_Drawing_Pen *, bool) | Checks whether anti-aliasing is enabled for a pen. If anti-aliasing is enabled, edges will be drawn with partial transparency.|
| OH_Drawing_PenSetWidth (OH_Drawing_Pen *, float width) | Sets the thickness for a pen. This thickness determines the width of the outline of a shape.|
| OH_Drawing_BrushCreate (void) | Creates a brush object.|
| OH_Drawing_BrushSetColor (OH_Drawing_Brush *, uint32_t color) | Sets the color for a brush. The color will be used by the brush to fill in a shape.|
| OH_Drawing_CreateTypographyStyle (void) | Creates a `TypographyStyle` object.|
| OH_Drawing_CreateTextStyle (void) | Creates a `TextStyle` object.|
| OH_Drawing_TypographyHandlerAddText (OH_Drawing_TypographyCreate *, const char *) | Sets the text content.|
| OH_Drawing_TypographyPaint (OH_Drawing_Typography *, OH_Drawing_Canvas *, double, double) | Paints text on the canvas.|
## Development Procedure for 2D Graphics Drawing
The following steps describe how to use the canvas and brush of the Native Drawing module to draw a 2D graphics.
1. **Create a bitmap object.** Use `OH_Drawing_BitmapCreate` in `drawing_bitmap.h` to create a bitmap object (named `cBitmap` in this example), and use `OH_Drawing_BitmapBuild` to specify its length, width, and pixel format.
```c++
// Create a bitmap object.
OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate();
// Define the pixel format of the bitmap.
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUYE};
// Set the pixel format for the bitmap.
OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat);
```
2. **Create a canvas object.** Use `OH_Drawing_CanvasCreate` in `drawing_canvas.h` to create a canvas object (named `cCanvas` in this example), and use `OH_Drawing_CanvasBind` to bind `cBitmap` to this canvas. The content drawn on the canvas will be output to the bound `cBitmap` object.
```c++
// Create a canvas object.
OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate();
// Bind the bitmap to the canvas. The content drawn on the canvas will be output to the bound bitmap memory.
OH_Drawing_CanvasBind(cCanvas, cBitmap);
// Use white to clear the canvas.
OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
```
3. **Construct a shape.** Use the APIs provided in `drawing_path.h` to draw a pentagram `cPath`.
```c++
int len = 300;
float aX = 500;
float aY = 500;
float dX = aX - len * std::sin(18.0f);
float dY = aY + len * std::cos(18.0f);
float cX = aX + len * std::sin(18.0f);
float cY = dY;
float bX = aX + (len / 2.0);
float bY = aY + std::sqrt((cX - dX) * (cX - dX) + (len / 2.0) * (len / 2.0));
float eX = aX - (len / 2.0);
float eY = bY;
// Create a path object and use the APIs to draw a pentagram.
OH_Drawing_Path* cPath = OH_Drawing_PathCreate();
// Specify the start point of the path.
OH_Drawing_PathMoveTo(cPath, aX, aY);
// Draw a line segment from the last point of a path to the target point.
OH_Drawing_PathLineTo(cPath, bX, bY);
OH_Drawing_PathLineTo(cPath, cX, cY);
OH_Drawing_PathLineTo(cPath, dX, dY);
OH_Drawing_PathLineTo(cPath, eX, eY);
// Close the path. Now the path is drawn.
OH_Drawing_PathClose(cPath);
```
4. **Set the brush and pen styles.** Use `OH_Drawing_PenCreate` in `drawing_pen.h` to create a pen (named `cPen` in this example), and set the attributes such as the anti-aliasing, color, and thickness. The pen is used to outline a shape. Use `OH_Drawing_BrushCreate` in `drawing_brush.h` to create a brush (named `cBrush` in this example), and set the brush color. The brush is used to fill in a shape. Use `OH_Drawing_CanvasAttachPen` and `OH_Drawing_CanvasAttachBrush` in `drawing_canvas.h` to attach the pen and brush to the canvas.
```c++
// Create a pen object and set the anti-aliasing, color, and thickness.
OH_Drawing_Pen* cPen = OH_Drawing_PenCreate();
OH_Drawing_PenSetAntiAlias(cPen, true);
OH_Drawing_PenSetColor(cPen, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x00, 0x00));
OH_Drawing_PenSetWidth(cPen, 10.0);
OH_Drawing_PenSetJoin(cPen, LINE_ROUND_JOIN);
// Attach the pen to the canvas.
OH_Drawing_CanvasAttachPen(cCanvas, cPen);
// Create a brush object and set the color.
OH_Drawing_Brush* cBrush = OH_Drawing_BrushCreate();
OH_Drawing_BrushSetColor(cBrush, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0xFF, 0x00));
// Attach the brush to the canvas.
OH_Drawing_CanvasAttachBrush(cCanvas, cBrush);
```
5. **Draw a shape.** Use `OH_Drawing_CanvasDrawPath` in `drawing_canvas.h` to draw a pentagram on the canvas. Call the corresponding APIs to destroy the objects when they are no longer needed.
```c++
// Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush.
OH_Drawing_CanvasDrawPath(cCanvas, cPath);
// Destroy the created objects when they are no longer needed.
OH_Drawing_BrushDestory(cBrush);
OH_Drawing_PenDestory(cPen);
OH_Drawing_PathDestory(cPath);
```
6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas.
```c++
// Obtain the pixel address after drawing. The memory to which the address points contains the pixel data of the drawing on the canvas.
void* bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap);
auto ret = memcpy_s(addr, addrSize, bitmapAddr, addrSize);
if (ret != EOK) {
LOGI("memcpy_s failed");
}
// Destroy the canvas object.
OH_Drawing_CanvasDestory(cCanvas);
// Destroy the bitmap object.
OH_Drawing_BitmapDestory(cBitmap);
```
## Development Procedure for Text Drawing and Display
The following steps describe how to use the text drawing and display feature of the Native Drawing module.
1. **Create a canvas and a bitmap.**
```c++
// Create a bitmap.
OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate();
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE};
OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat);
// Create a canvas.
OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate();
OH_Drawing_CanvasBind(cCanvas, cBitmap);
OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
```
2. **Set the typography style.**
```c++
// Set the typography attributes such as left to right (LTR) for the text direction and left-aligned for the text alignment mode.
OH_Drawing_TypographyStyle* typoStyle = OH_Drawing_CreateTypographyStyle();
OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR);
OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT);
```
3. **Set the text style.**
```c++
// Set the text color, for example, black.
OH_Drawing_TextStyle* txtStyle = OH_Drawing_CreateTextStyle();
OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00));
// Set text attributes such as the font size and weight.
double fontSize = 30;
OH_Drawing_SetTextStyleFontSize(txtStyle, fontSize);
OH_Drawing_SetTextStyleFontWeight(txtStyle, FONT_WEIGHT_400);
OH_Drawing_SetTextStyleBaseLine(txtStyle, TEXT_BASELINE_ALPHABETIC);
OH_Drawing_SetTextStyleFontHeight(txtStyle, 1);
// Set the font families.
const char* fontFamilies[] = {"Roboto"};
OH_Drawing_SetTextStyleFontFamilies(txtStyle, 1, fontFamilies);
OH_Drawing_SetTextStyleFontStyle(txtStyle, FONT_STYLE_NORMAL);
OH_Drawing_SetTextStyleLocale(txtStyle, "en");
```
4. **Generate the final text display effect.**
```c++
OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle,
OH_Drawing_CreateFontCollection());
OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle);
// Set the text content.
const char* text = "OpenHarmony\n";
OH_Drawing_TypographyHandlerAddText(handler, text);
OH_Drawing_TypographyHandlerPopTextStyle(handler);
OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(handler);
// Set the maximum width.
double maxWidth = 800.0;
OH_Drawing_TypographyLayout(typography, maxWidth);
// Set the start position for text display.
double position[2] = {10.0, 15.0};
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
```
## Samples
The following samples are provided to help you better understand how to use the Native Drawing module:
* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp)
* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp)
......@@ -4,7 +4,7 @@
## When to Use
This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. The table below describes the APIs.
This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to traverse, open, search for, read, and close raw files.
## Available APIs
......@@ -16,14 +16,14 @@ This document describes how to use the native Rawfile APIs to manage raw file di
| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. |
| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. |
| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. |
| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a data read/write position in a raw file based on the specified offset. |
| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset. |
| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. |
| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. |
| void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. |
| void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. |
| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file description (FD) of a raw file. |
| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file. |
| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. |
| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases native resource manager resources. |
| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager. |
## How to Develop
......@@ -38,7 +38,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance.
```js
// Call the JS API to pass the JS resource manager.
// Import the JS resource manager from the JS head file and pass it to the C++ file.
import resManager from '@ohos.resourceManager'
import rawfileTest from 'librawFileTest.so'
resManager.getResourceManager().then(resmgr => {
......@@ -49,7 +49,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
```
```c++
// The C++ API obtains and parses the parameters passed by the JS API.
// Obtain and parse the parameters in the C++ file.
NativeResourceManager* nativeResourceManager = nullptr;
std::string path;
if (i == 0 && valueType == napi_string) {
......@@ -57,7 +57,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
......
path = buf.data();
} else if (i == 1 && valueType == napi_object) {
// Parse the second parameter, which is the resource manager.
// Parse the second parameter, which is the JS resource manager.
nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]);
}
```
......@@ -80,7 +80,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file based on the specified index.
5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index.
```c++
for (int index = 0; index < count; index++) {
......@@ -90,7 +90,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance based on the specified file name.
6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name.
```c++
RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str());
......@@ -106,7 +106,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
8. Call **OH_ResourceManager_SeekRawFile** to seek a data read/write position in the raw file based on the specified offset.
8. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset.
```c++
int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0);
......@@ -124,7 +124,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
10. Call **OH_ResourceManager_ReadRawFile** to read a raw file.
10. Call **OH_ResourceManager_ReadRawFile** to read the raw file.
```c++
std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize);
......@@ -149,7 +149,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain **RawFileDescriptor** of the raw file.
13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file.
```c++
RawFileDescriptor descriptor;
......
......@@ -2,9 +2,9 @@
The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell.
### cem Debugging Assistant
## cem Debugging Assistant
##### publish
### publish
* Functionality
......@@ -41,7 +41,7 @@ The common event and notification module provides debugging tools to facilitate
![cem-publish-all](figures/cem-publish-all.png)
##### dump
### dump
* Functionality
......@@ -67,7 +67,7 @@ The common event and notification module provides debugging tools to facilitate
​ ![cem-dump-e](figures/cem-dump-e.png)
##### help
### help
* Functionality
......@@ -83,9 +83,9 @@ The common event and notification module provides debugging tools to facilitate
### anm Debugging Assistant
## anm Debugging Assistant
##### dump
### dump
* Functionality
......@@ -119,7 +119,7 @@ The common event and notification module provides debugging tools to facilitate
Set the number of the cached recent notifications to be displayed to 10.
##### help
### help
* Functionality
......
# Common Event Development
### Introduction
## Introduction
OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events.
Common events are classified into system common events and custom common events.
......@@ -25,13 +25,13 @@ You can create a subscriber object to subscribe to a common event to obtain the
### How to Develop
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent';
```
2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo).
```javascript
```js
private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information
......@@ -42,7 +42,7 @@ var subscribeInfo = {
3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription.
```javascript
```js
// Callback for subscriber creation.
commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
if (err.code) {
......@@ -57,7 +57,7 @@ commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata).
```javascript
```js
// Callback for common event subscription.
if (this.subscriber != null) {
commonEvent.subscribe(this.subscriber, (err, data) => {
......@@ -74,7 +74,7 @@ if (this.subscriber != null) {
}
```
## Public Event Publishing Development
## Common Event Publishing Development
### When to Use
You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process.
......@@ -89,13 +89,13 @@ You can use the **publish** APIs to publish a custom common event, which can car
#### Development for Publishing a Common Event
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent';
```
2. Pass in the common event name and callback, and publish the event.
```javascript
```js
// Publish a common event.
commonEvent.publish("event", (err) => {
if (err.code) {
......@@ -109,13 +109,13 @@ commonEvent.publish("event", (err) => {
#### Development for Publishing a Common Event with Given Attributes
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent'
```
2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata).
```javascript
```js
// Attributes of a common event.
var options = {
code: 1, // Result code of the common event
......@@ -125,7 +125,7 @@ var options = {
3. Pass in the common event name, attributes of the common event, and callback, and publish the event.
```javascript
```js
// Publish a common event.
commonEvent.publish("event", options, (err) => {
if (err.code) {
......@@ -149,14 +149,14 @@ You can use the **unsubscribe** API to unsubscribe from a common event.
### How to Develop
1. Import the **commonEvent** module.
```javascript
```js
import commonEvent from '@ohos.commonEvent';
```
2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development).
3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event.
```javascript
```js
if (this.subscriber != null) {
commonEvent.unsubscribe(this.subscriber, (err) => {
if (err.code) {
......
......@@ -4,26 +4,26 @@
### System Capabilities and APIs
SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each system capability corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in the IDE for association.
SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs are provided in DevEco Studio for association.
![image-20220326064841782](figures/image-20220326064841782.png)
### Supported Capability Set, Associated Capability Set, and Required Capability Set
### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set
The supported capability set, associated capability set, and required capability set are collections of system capabilities.
The supported capability set covers the device capabilities, and the required capability set covers the application capabilities. If the capability set required by application A is a subset of the capability set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed.
The associated capability set covers the system capabilities of associated APIs that the IDE offers during application development.
The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps.
The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed.
The associated SysCap set covers the system capabilities of associated APIs that the IDE offers during application development.
![image-20220326064913834](figures/image-20220326064913834.png)
### Devices and Supported Capability Sets
### Devices and Supported SysCap Sets
Each device provides a capability set that matches its hardware capability.
The SDK classifies devices into general devices and custom devices. The general devices' supported capability set is defined by OpenHarmony, and the custom devices' is defined by device vendors.
Each device provides a SysCap set that matches its hardware capability.
The SDK classifies devices into general devices and custom devices. The general devices' supported SysCap set is defined by OpenHarmony, and the custom devices' is defined by device vendors.
![image-20220326064955505](figures/image-20220326064955505.png)
......@@ -31,7 +31,7 @@ The SDK classifies devices into general devices and custom devices. The general
### Mapping Between Devices and SDK Capabilities
The SDK provides a full set of APIs for the IDE. The IDE identifies the supported capability set based on the devices supported by the project, filters the APIs contained in the capability set, and provides the supported APIs for association (to autocomplete input).
The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input).
![image-20220326065043006](figures/image-20220326065043006.png)
......@@ -49,11 +49,11 @@ Right-click the project directory and choose **Import Product Compatibility ID**
### Configuring the Associated Capability Set and Required Capability Set
### Configuring the Associated SysCap Set and Required SysCap Set
The IDE automatically configures the associated capability set and required capability set based on the settings supported by the created project. You can modify the capability sets when necessary.
You can add APIs to the associated capability set in the IDE by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them.
Exercise caution when modifying the required capability set. Incorrect modifications may result in the application being unable to be distributed to the target device.
DevEco Studio automatically configures the associated SysCap set and required SysCap set based on the settings supported by the created project. You can modify these SysCap sets when necessary.
You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them.
Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device.
```
/* syscap.json */
......@@ -74,15 +74,15 @@ Exercise caution when modifying the required capability set. Incorrect modificat
...
]
},
development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated capability set. */
development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */
addedSysCaps: [
"SystemCapability.Location.Location.Lite",
...
]
},
production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */
addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required capability set with addedSysCaps set and removedSysCaps set.
removedSysCaps: [] // When the required capability set is a capability subset of a device, the application can be distributed to the device.
addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set.
removedSysCaps: [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device.
}
}
```
......@@ -91,7 +91,7 @@ Exercise caution when modifying the required capability set. Incorrect modificat
### Single-Device Application Development
By default, the associated capability set and required system capability set of the application are the same as the supported system capability set of the device. Exercise caution when modifying the required capability set.
By default, the associated SysCap set and required SysCap set of the application are the same as the supported SysCap set of the device. Exercise caution when modifying the required SysCap set.
![image-20220326065124911](figures/image-20220326065124911.png)
......@@ -99,7 +99,7 @@ By default, the associated capability set and required system capability set of
### Cross-Device Application Development
By default, the associated capability set of an application is the union of multiple devices' supported capability sets, while the required capability set is the intersection of the devices' supported capability sets.
By default, the associated SysCap set of an application is the union of multiple devices' supported SysCap sets, while the required SysCap set is the intersection of the devices' supported SysCap sets.
![image-20220326065201867](figures/image-20220326065201867.png)
......@@ -133,9 +133,9 @@ if (geolocation) {
### Checking the Differences Between Devices with the Same Capability
### Checking the Differences Between Devices with a Specific SysCap
The performance of a system capability may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability.
The performance of a SysCap may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability.
```
import userAuth from '@ohos.userIAM.userAuth';
......@@ -162,7 +162,7 @@ The device SysCaps in product solutions vary according to the component combinat
![image-20220326072448840](figures/image-20220326072448840.png)
1. A set of OpenHarmony source code consists of optional and mandatory components. Different components have different system capabilities. In other words, different components represent different SysCaps.
1. A set of OpenHarmony source code consists of optional and mandatory components. Different components represent different SysCaps.
2. In a normalized released SDK, APIs are mapped to SysCap sets.
......@@ -170,10 +170,10 @@ The device SysCaps in product solutions vary according to the component combinat
4. The components configured for a product can be OpenHarmony components or proprietary components developed by a third party. Since there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled.
5. The SysCap set is encoded to generate the PCID. You can import the PCID to the IDE and decode it into SysCap. During development, compatibility processing is performed to mitigate the SysCap differences of devices.
5. The SysCap set is encoded to generate the PCID. You can import the PCID to DevEco Studio and decode it into SysCaps. During development, compatibility processing is performed to mitigate the SysCap differences of devices.
6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications to check whether a specific SysCap is available.
7. During application development, the SysCap required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap required by the application and compares it with the SysCap of the device. If the SysCap required by the application is met, the application can be installed.
7. During application development, the SysCap set required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap set required by the application and compares it with the SysCap set supported by the device. If the SysCap set required by the application is met, the application can be installed on the device.
8. When an application is running on a device, the **canIUse** API can be used to query whether the device is compatible with a specific SysCap.
# Context Module
> **NOTE**<br/>
> 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.
> **NOTE**
>
> 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 APIs of this module can be used only in the FA model.
## Modules to Import
......@@ -834,7 +836,7 @@ Obtains information of the current ability. This API uses an asynchronous callba
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------- |
| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes |Callback used to return the ability information.|
| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes | Callback used to return the ability information.|
**Example**
......@@ -886,7 +888,7 @@ Obtains the context of the application.
| Type | Description |
| --------- |------ |
| Context |Application context.|
| Context | Application context.|
**Example**
......@@ -928,14 +930,14 @@ Describes the HAP module information.
| labelId | number | Yes | No | Module label ID. |
| iconId | number | Yes | No | Module icon ID. |
| backgroundImg | string | Yes | No | Module background image. |
| supportedModes | number | Yes | No | Modes supported by the module. |
| supportedModes | number | Yes | No | Running modes supported by the module. |
| reqCapabilities | Array<string> | Yes | No | Capabilities required for module running.|
| deviceTypes | Array<string> | Yes | No | An array of supported device types.|
| abilityInfo | Array<AbilityInfo> | Yes | No | Ability information. |
| deviceTypes | Array<string> | Yes | No | Device types supported by the module.|
| abilityInfo | Array<AbilityInfo> | Yes | No | Ability information. |
| moduleName | string | Yes | No | Module name. |
| mainAbilityName | string | Yes | No | Name of the entrance ability. |
| installationFree | boolean | Yes | No | When installation-free is supported. |
| mainElementName | string | Yes| No| Information about the entry ability.|
| mainAbilityName | string | Yes | No | Name of the main ability. |
| installationFree | boolean | Yes | No | Whether installation-free is supported. |
| mainElementName | string | Yes| No| Information about the main ability.|
## AppVersionInfo<sup>7+</sup>
......
# AbilityContext
> **NOTE**<br/>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Implements the ability context. This module is inherited from **Context**.
......@@ -55,7 +57,7 @@ Starts an ability. This API uses a callback to return the result.
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "com.extreme.test.MainAbility"
"abilityName": "MainAbility"
};
this.context.startAbility(want, (error) => {
console.log("error.code = " + error.code)
......@@ -85,7 +87,7 @@ Starts an ability. This API uses a callback to return the result.
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "com.extreme.test.MainAbility"
"abilityName": "MainAbility"
};
var options = {
windowMode: 0,
......@@ -123,7 +125,7 @@ Starts an ability. This API uses a promise to return the result.
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "com.extreme.test.MainAbility"
"abilityName": "MainAbility"
};
var options = {
windowMode: 0,
......@@ -374,7 +376,7 @@ Obtains the caller interface of the specified ability, and if the specified abil
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "com.example.myservice.MainAbility",
abilityName: "MainAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......
# Animation
# Animator
> **NOTE**<br>
> 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.
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>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
**requestAnimationFrame**: none
```
import animator from '@ohos.animator';
```
## createAnimator
createAnimator(options: AnimatorOptions): AnimatorResult
Creates an **Animator** object.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.|
**Return value**
| Type| Description|
| -------- | -------- |
| [AnimatorResult](#animatorresult) | Animator result.|
**Example**
```
<!-- hml -->
<div class="container">
<div class="Animation" style="height: {{divHeight}}px; width: {{divWidth}}px; background-color: red;" onclick="Show">
</div>
</div>
```
```
// js
export default {
data : {
divWidth: 200,
divHeight: 200,
animator: null
},
onInit() {
var options = {
duration: 1500,
easing: 'friction',
fill: 'forwards',
iterations: 2,
begin: 200.0,
end: 400.0
};
this.animator = animator.createAnimator(options);
},
Show() {
var options1 = {
duration: 2000,
easing: 'friction',
fill: 'forwards',
iterations: 1,
begin: 200.0,
end: 400.0
};
this.animator.update(options1);
var _this = this;
this.animator.onframe = function(value) {
_this.divWidth = value;
_this.divHeight = value;
};
this.animator.play();
}
}
```
## AnimatorResult
Defines the animator result.
### update
update(options: AnimatorOptions): void
Updates this animator.
**cancelAnimationFrame**: none
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**createAnimator**:
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.|
**Example**
```
import animator from '@ohos.animator';
animator.update(options);
```
## Required Permissions
### play
None
play(): void
## requestAnimationFrame
Plays this animation.
requestAnimationFrame\(handler\[, \[ ...args\]\]\): number
**System capability**: SystemCapability.ArkUI.ArkUI.Full
Requests an animation frame.
**Example**
```
animator.play();
```
- Parameters
### finish
| Name | Type | Mandatory | Description |
| ------- | ----------- | --------- | ------------------------------------------------------------ |
| handler | Function | Yes | Handler used to request a frame. When **requestAnimationFrame** calls the **handler**, the timestamp is passed to the first parameter to indicate the time when **requestAnimationFrame** starts to execute the callback. |
| ...args | Array\<any> | No | Additional parameter, which is passed to the **handler** as a parameter during function callback. |
finish(): void
- Return values
Ends this animation.
| Type | Description |
| ------ | ----------- |
| number | Request ID. |
- Example
**System capability**: SystemCapability.ArkUI.ArkUI.Full
```
<!-- xxx.hml -->
<div class="container">
<button type="capsule" class="btn" onclick="beginAnimation">beginAnimation</button>
</div>
```
```
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.btn{
width: 300px;
margin-top: 40px;
}
```
```
/* xxx.js */
export default {
data: {
requestId: 0,
startTime: 0,
},
beginAnimation() {
cancelAnimationFrame(this.requestId);
this.requestId = requestAnimationFrame(this.runAnimation);
},
runAnimation(timestamp) {
if (this.startTime == 0) {
this.startTime = timestamp;
}
var elapsed = timestamp - this.startTime;
if (elapsed < 500) {
console.log('callback handler timestamp: ' + timestamp);
this.requestId = requestAnimationFrame(this.runAnimation);
}
}
}
```
**Example**
```
animator.finish();
```
### pause
## cancelAnimationFrame
pause(): void
cancelAnimationFrame\(requestId: number\): void
Pauses this animation.
Cancels the animation frame request.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
- Parameters
**Example**
```
animator.pause();
```
| Name | Type | Mandatory | Description |
| --------- | ------ | --------- | ------------------------ |
| requestId | number | Yes | ID of the frame request. |
- Example
### cancel
```
<!-- xxx.hml -->
<div class="container">
<button type="capsule" class="btn" onclick="beginAnimation">beginAnimation</button>
<button type="capsule" class="btn" onclick="beginAnimation">stopAnimation</button>
</div>
```
```
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.btn{
width: 300px;
margin-top: 40px;
}
```
```
/* xxx.js */
export default {
data: {
requestId: 0,
startTime: 0,
},
beginAnimation() {
cancelAnimationFrame(this.requestId);
this.requestId = requestAnimationFrame(this.runAnimation);
},
runAnimation(timestamp) {
if (this.startTime == 0) {
this.startTime = timestamp;
}
var elapsed = timestamp - this.startTime;
if (elapsed < 500) {
console.log('callback handler timestamp: ' + timestamp);
this.requestId = requestAnimationFrame(this.runAnimation);
}
},
stopAnimation() {
cancelAnimationFrame(this.requestId);
}
}
```
cancel(): void
Cancels this animation.
## createAnimator
**System capability**: SystemCapability.ArkUI.ArkUI.Full
createAnimator\(options\[...\]\): void
Creates an animation object.
- Parameters
| Name | Type | Mandatory | Description |
| ------- | ------ | --------- | ------------------------------------------------------------ |
| options | Object | Yes | Attributes of the **Animator** to be created. For details, see the options table. |
- Description of options
| Name | Type | Mandatory | Description |
| ---------- | ------ | --------- | ------------------------------------------------------------ |
| duration | number | No | Duration for playing an animation, in milliseconds. The default value is **0**. |
| easing | string | No | Animation easing curve. The default value is **ease**. |
| delay | number | No | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. |
| fill | string | No | Animation start/stop mode. The default value is **none**. |
| direction | string | No | Animation playback mode. The default value is **normal**. |
| iterations | number | No | Number of times that an animation is played. The default value is **1**. If this parameter is set to **0**, the animation is not played. If this parameter is set to **-1**, the animation is played for an unlimited number of times. |
| begin | number | No | Start point of the animation easing. If this parameter is not set, the default value **0** is used. |
| end | number | No | End point of the animation easing. If this parameter is not set, the default value **1** is used. |
- animator interfaces
| Name | Type | Description |
| ------- | ------- | ------------------------------------------------------------ |
| update | options | Updates the animation parameters. The input parameters are the same as those of **createAnimator**. |
| play | - | Starts an animation. |
| finish | - | Ends an animation. |
| pause | - | Pauses an animation. |
| cancel | - | Cancels an animation. |
| reverse | - | Reverses an animation. |
- **animator** supported events:
| Name | Type | Description |
| ------ | ------ | ----------------------------------- |
| frame | number | The frame is requested. |
| cancel | - | The animation is forcibly canceled. |
| finish | - | The animation playback is complete. |
| repeat | - | The animation replays. |
- Example
```
<!-- hml -->
<div class="container">
<div class="Animation" style="height: {{divHeight}}px; width: {{divWidth}}px; background-color: red;" onclick="Show">
</div>
</div>
```
```
// js
export default {
data : {
divWidth: 200,
divHeight: 200,
animator: null
},
onInit() {
var options = {
duration: 1500,
easing: 'friction',
fill: 'forwards',
iterations: 2,
begin: 200.0,
end: 400.0
};
this.animator = animator.createAnimator(options);
},
Show() {
var options1 = {
duration: 2000,
easing: 'friction',
fill: 'forwards',
iterations: 1,
begin: 200.0,
end: 400.0
};
this.animator.update(options1);
var _this = this;
this.animator.onframe = function(value) {
_this.divWidth = value;
_this.divHeight = value;
};
this.animator.play();
}
}
```
\ No newline at end of file
**Example**
```
animator.cancel();
```
### reverse
reverse(): void
Plays this animation in reverse order.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.reverse();
```
### onframe
onframe: (progress: number) => void
Called when a frame is received.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| progress | number | Yes| Current progress of the animation.|
**Example**
```
animator.onframe();
```
### onfinish
onfinish: () => void
Called when this animation is finished.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.onfinish();
```
### oncancel
oncancel: () => void
Called when this animation is canceled.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.oncancel();
```
### onrepeat
onrepeat: () => void
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.onrepeat();
```
Called when this animation repeats.
## AnimatorOptions
Defines animator options.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.|
| easing | string | Yes| Animation interpolation curve. The default value is **ease**.|
| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.|
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. |
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.|
| iterations | number | Yes| Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.|
| begin | number | Yes| Start point of the animation interpolation. If this parameter is not set, the default value **0** is used.|
| end | number | Yes| End point of the animation interpolation. If this parameter is not set, the default value **1** is used.|
# Want
> **NOTE**<br/>
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
**Want** is the basic communication component of the system.
## Modules to Import
```
import Want from '@ohos.application.Want';
```
......@@ -17,14 +16,15 @@ import Want from '@ohos.application.Want';
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Readable/Writable | Type | Mandatory | Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | Read only | string | No | ID of the device running the ability. |
| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability. |
| abilityName | Read only | string | No | Name of the ability. If both **package** and **AbilityName** are specified in this field in a **Want** object, the **Want** object can directly match the specified ability. |
| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**. |
| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. |
| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags). |
| action | Read only | string | No | Action option. |
| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. |
| entities | Read only | Array\<string> | No | List of entities. |
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | Read only | string | No | ID of the device running the ability. |
| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.|
| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. |
| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).|
| action | Read only | string | No | Action option. |
| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. |
| entities | Read only | Array\<string> | No | List of entities. |
| moduleName<sup>9+</sup> | Read only | string | No | Module to which the ability belongs. Different abilities among HAP files in an application may use the same name. If the abilities cannot be distinguished by the combination of **bundleName** and **abilityName**, you can set **moduleName** for better distinguishing.| |
# Ability
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Manages the ability lifecycle and context.
## Modules to Import
```
import Ability from '@ohos.application.Ability';
```
......@@ -23,6 +22,8 @@ import Ability from '@ohos.application.Ability';
| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.|
| launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.|
| lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.|
| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.|
## Ability.onCreate
......@@ -200,11 +201,12 @@ Called to save data during the ability migration preparation process.
**Example**
```js
import AbilityConstant from "@ohos.application.AbilityConstant"
class myAbility extends Ability {
onContinue(wantParams) {
console.log('onContinue');
wantParams["myData"] = "my1234567";
return true;
return AbilityConstant.OnContinueResult.AGREE;
}
}
```
......@@ -212,7 +214,7 @@ Called to save data during the ability migration preparation process.
## Ability.onNewWant
onNewWant(want: Want): void;
onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void;
Called when the ability startup mode is set to singleton.
......@@ -223,13 +225,17 @@ Called when the ability startup mode is set to singleton.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.|
| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.|
**Example**
```js
class myAbility extends Ability {
onNewWant(want) {
onNewWant(want, launchParams) {
console.log('onNewWant, want:' + want.abilityName);
if (launchParams.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
console.log('onNewWant, launchReason is continuation');
}
}
}
```
......@@ -259,6 +265,32 @@ Called when the configuration of the environment where the ability is running is
}
```
## Ability.dump
dump(params: Array\<string>): Array\<string>;
Called when the client information is dumped.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
```js
class myAbility extends Ability {
dump(params) {
console.log('dump, params:' + JSON.stringify(params));
return ["params"]
}
}
```
## Caller
......@@ -291,6 +323,9 @@ Sends sequenceable data to the target ability.
```js
import Ability from '@ohos.application.Ability';
class MyMessageAble{ // Custom sequenceable data structure
name:""
str:""
num: 1
constructor(name, str) {
this.name = name;
this.str = str;
......@@ -314,7 +349,7 @@ Sends sequenceable data to the target ability.
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "com.example.myservice.MainAbility",
abilityName: "MainAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -361,6 +396,9 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
```js
import Ability from '@ohos.application.Ability';
class MyMessageAble{
name:""
str:""
num: 1
constructor(name, str) {
this.name = name;
this.str = str;
......@@ -384,7 +422,7 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "com.example.myservice.MainAbility",
abilityName: "MainAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -423,7 +461,7 @@ Releases the caller interface of the target ability.
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "com.example.myservice.MainAbility",
abilityName: "MainAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -445,7 +483,7 @@ Releases the caller interface of the target ability.
onRelease(callback: OnReleaseCallBack): void;
Registers a callback that is invoked when the Stub on the target ability is disconnected.
Registers a callback that is invoked when the stub on the target ability is disconnected.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
......@@ -464,7 +502,7 @@ Registers a callback that is invoked when the Stub on the target ability is disc
onWindowStageCreate(windowStage) {
this.context.startAbilityByCall({
bundleName: "com.example.myservice",
abilityName: "com.example.myservice.MainAbility",
abilityName: "MainAbility",
deviceId: ""
}).then((obj) => {
caller = obj;
......@@ -509,6 +547,9 @@ Registers a caller notification callback, which is invoked when the target abili
```js
import Ability from '@ohos.application.Ability';
class MyMessageAble{
name:""
str:""
num: 1
constructor(name, str) {
this.name = name;
this.str = str;
......
# ApplicationContext
> **NOTE**<br>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
Provides application-level context and APIs for registering and deregistering the ability lifecycle listener in an application.
......@@ -41,14 +42,6 @@ Registers a listener to monitor the ability lifecycle of the application.
| ------ | ------------------------------ |
| number | ID of the registered listener. The ID is incremented by 1 each time the listener is registered. When the ID exceeds 2^63-1, **-1** is returned.|
**Example**
```js
let applicationContext = this.context.getApplicationContext();
console.log("stage applicationContext: " + JSON.stringify(applicationContext));
let lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));
```
## ApplicationContext.unregisterAbilityLifecycleCallback
......@@ -68,9 +61,47 @@ Deregisters the listener that monitors the ability lifecycle of the application.
**Example**
```js
let applicationContext = this.context.getApplicationContext();
console.log("stage applicationContext: " + JSON.stringify(applicationContext));
applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
});
import AbilityStage from "@ohos.application.AbilityStage";
var lifecycleid;
export default class MyAbilityStage extends AbilityStage {
onCreate() {
console.log("MyAbilityStage onCreate")
let AbilityLifecycleCallback = {
onAbilityCreate(ability){
console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability));
},
onAbilityWindowStageCreate(ability){
console.log("AbilityLifecycleCallback onAbilityWindowStageCreate ability:" + JSON.stringify(ability));
},
onAbilityWindowStageDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityWindowStageDestroy ability:" + JSON.stringify(ability));
},
onAbilityDestroy(ability){
console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability));
},
onAbilityForeground(ability){
console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability));
},
onAbilityBackground(ability){
console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability));
},
onAbilityContinue(ability){
console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability));
}
}
// 1. Obtain applicationContext through the context attribute.
let applicationContext = this.context.getApplicationContext();
// 2. Use applicationContext to register a listener for the ability lifecycle in the application.
lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback);
console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid));
}
onDestroy() {
let applicationContext = this.context.getApplicationContext();
applicationContext.unregisterAbilityLifecycleCallback(lifecycleid, (error, data) => {
console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error));
});
}
}
```
......@@ -175,6 +175,17 @@ cameraManager.getCameras().then((cameraArray) => {
})
```
### Size
Size parameters. This interface used to get supported size for Preview + Photo + Video.
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Default Value | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ----------------------------------- |
| height | number | Yes | Desired height of the Preview + Photo + Video. |
| width | number | Yes | Desired width of the Preview + Photo + Video.|
### createCameraInput
createCameraInput(cameraId: string, callback: AsyncCallback<CameraInput\>): void
......@@ -249,7 +260,7 @@ Creates a **CameraInput** instance with the specified camera position and camera
**Example**
```
cameraManager.createCameraInput(cameraPosition, cameraType, (err, cameraInput) => {
cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => {
if (err) {
console.error('Failed to create the CameraInput instance. ${err.message}');
return;
......@@ -282,7 +293,7 @@ Creates a **CameraInput** instance with the specified camera position and camera
**Example**
```
cameraManager.createCameraInput(cameraPosition, cameraType).then((cameraInput) => {
cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => {
console.log('Promise returned with the CameraInput instance.');
})
```
......@@ -305,7 +316,11 @@ Listens for camera status changes. This API uses a callback to return the camera
**Example**
```
cameraManager.on('cameraStatus', (cameraStatusInfo) => {
cameraManager.on('cameraStatus', (err, cameraStatusInfo) => {
if (err) {
console.error('Failed to get cameraStatus callback. ${err.message}');
return;
}
console.log('camera : ' + cameraStatusInfo.camera.cameraId);
console.log('status: ' + cameraStatusInfo.status);
})
......@@ -327,14 +342,14 @@ After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera
**Example**
```
async function getCameraInfo() {
async function getCameraInfo("cameraId") {
var cameraManager = await camera.getCameraManager();
var cameras = await cameraManager.getCameras();
var cameraObj = cameras[0];
var cameraId = cameraObj.cameraId;
var cameraPosition = cameraObj.cameraPosition;
var cameraType = cameraObj.cameraType;
var cameraId = cameraObj.connectionType;
var connectionType = cameraObj.connectionType;
}
```
......@@ -470,7 +485,7 @@ Checks whether a specified flash mode is supported. This API uses an asynchronou
**Example**
```
cameraInput.isFlashModeSupported(flashMode, (err, status) => {
cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => {
if (err) {
console.error('Failed to check whether the flash mode is supported. ${err.message}');
return;
......@@ -502,7 +517,7 @@ Checks whether a specified flash mode is supported. This API uses a promise to r
**Example**
```
cameraInput.isFlashModeSupported(flashMode).then((status) => {
cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => {
console.log('Promise returned with flash mode support status.' + status);
})
```
......@@ -530,7 +545,7 @@ Before setting the parameters, do the following checks:
**Example**
```
cameraInput.setFlashMode(flashMode, (err) => {
cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => {
if (err) {
console.error('Failed to set the flash mode ${err.message}');
return;
......@@ -567,7 +582,7 @@ Before setting the parameters, do the following checks:
**Example**
```
cameraInput.setFlashMode(flashMode).then(() => {
cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => {
console.log('Promise returned with the successful execution of setFlashMode.');
})
```
......@@ -638,7 +653,7 @@ Checks whether a specified focus mode is supported. This API uses an asynchronou
**Example**
```
cameraInput.isFocusModeSupported(afMode, (err, status) => {
cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => {
if (err) {
console.error('Failed to check whether the focus mode is supported. ${err.message}');
return;
......@@ -670,7 +685,7 @@ Checks whether a specified focus mode is supported. This API uses a promise to r
**Example**
```
cameraInput.isFocusModeSupported(afMode).then((status) => {
cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => {
console.log('Promise returned with focus mode support status.' + status);
})
```
......@@ -695,7 +710,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte
**Example**
```
cameraInput.setFocusMode(afMode, (err) => {
cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => {
if (err) {
console.error('Failed to set the focus mode ${err.message}');
return;
......@@ -729,7 +744,7 @@ Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupporte
**Example**
```
cameraInput.setFocusMode(afMode).then(() => {
cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => {
console.log('Promise returned with the successful execution of setFocusMode.');
})
```
......@@ -848,7 +863,7 @@ Sets a zoom ratio. This API uses an asynchronous callback to return the result.
**Example**
```
cameraInput.setZoomRatio(zoomRatio, (err) => {
cameraInput.setZoomRatio(1, (err) => {
if (err) {
console.error('Failed to set the zoom ratio value ${err.message}');
return;
......@@ -880,7 +895,7 @@ Sets a zoom ratio. This API uses a promise to return the result.
**Example**
```
cameraInput.setZoomRatio(zoomRatio).then(() => {
cameraInput.setZoomRatio(1).then(() => {
console.log('Promise returned with the successful execution of setZoomRatio.');
})
```
......@@ -950,7 +965,7 @@ Releases this **CameraInput** instance. This API uses an asynchronous callback t
**Example**
```
camera.release((err) => {
cameraInput.release((err) => {
if (err) {
console.error('Failed to release the CameraInput instance ${err.message}');
return;
......@@ -1027,6 +1042,27 @@ cameraInput.on('error', (cameraInputError) => {
})
```
## CameraInputErrorCode
Enumerates the CameraInput error code.
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| ERROR_UNKNOWN | -1 | Unknown error.|
## CameraInputError
Camera input error object which extends **Error** interface.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Parameters**
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| code | [CameraInputErrorCode](#camerainputerrorcode) | Used to get error code in CameraInput on('error') callback|
## FlashMode
......@@ -1836,6 +1872,28 @@ captureSession.on('error', (captureSessionError) => {
})
```
## CaptureSessionErrorCode
Enumerates the CaptureSession error code.
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| ERROR_UNKNOWN | -1 | Unknown error.|
## CaptureSessionError
Capture session error object which extends **Error** interface.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Parameters**
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| code | [CaptureSessionErrorCode](#capturesessionerrorcode) | Used to get error code in CaptureSession on('error') callback.|
## camera.createPreviewOutput
createPreviewOutput(surfaceId: string, callback: AsyncCallback<PreviewOutput\>): void
......@@ -1854,7 +1912,7 @@ Creates a **PreviewOutput** instance. This API uses an asynchronous callback to
**Example**
```
camera.createPreviewOutput((surfaceId), (err, previewOutput) => {
camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => {
if (err) {
console.error('Failed to create the PreviewOutput instance. ${err.message}');
return;
......@@ -1886,7 +1944,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the inst
**Example**
```
camera.createPreviewOutput(surfaceId).then((previewOutput) => {
camera.createPreviewOutput("surfaceId").then((previewOutput) => {
console.log('Promise returned with the PreviewOutput instance');
})
```
......@@ -2013,6 +2071,28 @@ previewOutput.on('error', (previewOutputError) => {
})
```
## PreviewOutputErrorCode
Enumerates the PreviewOutput error code.
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| ERROR_UNKNOWN | -1 | Unknown error.|
## PreviewOutputError
Preview output error object which extends **Error** interface.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Parameters**
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | Used to get error code in PreviewOutput on('error') callback.|
## camera.createPhotoOutput
createPhotoOutput(surfaceId: string, callback: AsyncCallback<PhotoOutput\>): void
......@@ -2031,7 +2111,7 @@ Creates a **PhotoOutput** instance. This API uses an asynchronous callback to re
**Example**
```
camera.createPhotoOutput((surfaceId), (err, photoOutput) => {
camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => {
if (err) {
console.error('Failed to create the PhotoOutput instance. ${err.message}');
return;
......@@ -2063,7 +2143,7 @@ Creates a **PhotoOutput** instance. This API uses a promise to return the instan
**Example**
```
camera.createPhotoOutput(surfaceId).then((photoOutput) => {
camera.createPhotoOutput("surfaceId").then((photoOutput) => {
console.log('Promise returned with PhotoOutput instance');
})
```
......@@ -2260,7 +2340,7 @@ Listens for photo capture start events. This API uses a callback to return the e
**Example**
```
photoOutput.on('captureStart', (captureId) => {
photoOutput.on('captureStart', (err, captureId) => {
console.log('photo capture stated, captureId : ' + captureId);
})
```
......@@ -2336,6 +2416,50 @@ photoOutput.on('error', (photoOutputError) => {
})
```
### FrameShutterInfo
Frame shutter callback info which provides **captureId** & **timestamp** parameteres & indicates the frame shutter event.
**Parameteres**
| Name | Type | Mandatory| Description |
| :------- | :------------------------------- | :--- | :---------------------------------------- |
| captureId | number | Yes | Capture id.|
| timestamp | number | Yes | Timestamp for frame.
### CaptureEndInfo
Capture end info which provides **captureId** & **frameCount** parameteres & indicates the photo capture end event.
**Parameteres**
| Name | Type | Mandatory| Description |
| :------- | :------------------------------- | :--- | :---------------------------------------- |
| captureId | number | Yes | Capture id.|
| frameCount | number | Yes | Frame count.
## PhotoOutputErrorCode
Enumerates the PhotoOutput error code.
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| ERROR_UNKNOWN | -1 | Unknown error.|
## PhotoOutputError
Photo output error object which extends **Error** interface.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Parameters**
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Used to get error code in PhotoOutput on('error') callback.|
## camera.createVideoOutput
createVideoOutput(surfaceId: string, callback: AsyncCallback<VideoOutput\>): void
......@@ -2354,7 +2478,7 @@ Creates a **VideoOutput** instance. This API uses an asynchronous callback to re
**Example**
```
camera.createVideoOutput((surfaceId), (err, videoOutput) => {
camera.createVideoOutput(("surfaceId"), (err, videoOutput) => {
if (err) {
console.error('Failed to create the VideoOutput instance. ${err.message}');
return;
......@@ -2386,7 +2510,8 @@ Creates a **VideoOutput** instance. This API uses a promise to return the instan
**Example**
```
camera.createVideoOutput(surfaceId).then((videoOutput) => {
camera.createVideoOutput("surfaceId"
).then((videoOutput) => {
console.log('Promise returned with the VideoOutput instance');
})
```
......@@ -2609,3 +2734,25 @@ videoOutput.on('error', (VideoOutputError) => {
console.log('Video output error code: ' + VideoOutputError.code);
})
```
## VideoOutputErrorCode
Enumerates the VideoOutput error code.
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| ERROR_UNKNOWN | -1 | Unknown error.|
## VideoOutputError
Photo output error object which extends **Error** interface.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Parameters**
| Name | Default Value| Description |
| ---------------------- | ------ | ------------ |
| code | [VideoOutputErrorCode](#videooutputerrorcode) | Used to get error code in VideoOutput on('error') callback.|
\ No newline at end of file
# Standard NFC Card Emulation
This module is used to implement Near-Field Communication (NFC) card emulation.
Implements Near-Field Communication (NFC) card emulation.
> **NOTE**<br>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -45,7 +45,7 @@ Starts HCE.
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| aidList | string[] | Yes | Aid list to be registered for card emulation.|
| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.|
### stopHCE
......@@ -78,7 +78,7 @@ Subscribes to messages from the peer device after **startHCE()**.
sendResponse(responseApdu: number[]): void;
Sends data to the peer device.
Sends a response to the peer device.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
......
......@@ -195,7 +195,7 @@ Updates a contact based on the specified contact information and attributes. Thi
fullName: {fullName: 'xxx'},
phoneNumbers: [{phoneNumber: '138xxxxxxxx'}]
},{
attributes:['ATTR_EMAIL', 'ATTR_NAME']
attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err) => {
if (err) {
console.log('updateContact callback: err->${JSON.stringify(err)}');
......@@ -234,7 +234,7 @@ Updates a contact based on the specified contact information and attributes. Thi
fullName: {fullName: 'xxx'},
phoneNumbers: [{phoneNumber: '138xxxxxxxx'}]
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
});
promise.then(() => {
console.log('updateContact success');
......@@ -564,7 +564,9 @@ Queries contacts based on the specified key and application. This API uses an as
```js
contact.queryContact('xxx', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, (err, data) => {
if (err) {
console.log(`queryContact callback: err->${JSON.stringify(err)}`);
......@@ -596,7 +598,7 @@ Queries contacts based on the specified key and attributes. This API uses an asy
```js
contact.queryContact('xxx', {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContact callback: err->${JSON.stringify(err)}`);
......@@ -630,8 +632,11 @@ Queries contacts based on the specified key, application, and attributes. This A
```js
contact.queryContact('xxx', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContact callback: err->${JSON.stringify(err)}`);
......@@ -669,8 +674,11 @@ Queries contacts based on the specified key, application, and attributes. This A
```js
let promise = contact.queryContact('xxx', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
});
promise.then((data) => {
console.log(`queryContact success: data->${JSON.stringify(data)}`);
......@@ -728,7 +736,9 @@ Queries all contacts based on the specified application. This API uses an asynch
```js
contact.queryContacts({
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, (err, data) => {
if (err) {
console.log(`queryContacts callback: err->${JSON.stringify(err)}`);
......@@ -759,7 +769,7 @@ Queries all contacts based on the specified attributes. This API uses an asynchr
```js
contact.queryContacts({
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContacts callback: err->${JSON.stringify(err)}`);
......@@ -791,9 +801,11 @@ Queries all contacts based on the specified application and attributes. This API
```js
contact.queryContacts({
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContacts callback: err->${JSON.stringify(err)}`);
......@@ -829,9 +841,11 @@ Queries all contacts based on the specified application and attributes. This API
```js
let promise = contact.queryContacts({
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
});
promise.then((data) => {
console.log(`queryContacts success: data->${JSON.stringify(data)}`);
......@@ -891,7 +905,9 @@ Queries contacts based on the specified phone number and application. This API u
```js
contact.queryContactsByPhoneNumber('138xxxxxxxx', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, (err, data) => {
if (err) {
console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`);
......@@ -923,7 +939,7 @@ Queries contacts based on the specified phone number and attributes. This API us
```js
contact.queryContactsByPhoneNumber('138xxxxxxxx', {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`);
......@@ -956,9 +972,11 @@ Queries contacts based on the specified phone number, application, and attribute
```js
contact.queryContactsByPhoneNumber('138xxxxxxxx', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContactsByPhoneNumber callback: err->${JSON.stringify(err)}`);
......@@ -995,9 +1013,11 @@ Queries contacts based on the specified phone number, application, and attribute
```js
let promise = contact.queryContactsByPhoneNumber('138xxxxxxxx', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
});
promise.then((data) => {
console.log(`queryContactsByPhoneNumber success: data->${JSON.stringify(data)}`);
......@@ -1057,7 +1077,9 @@ Queries contacts based on the specified email address and application. This API
```js
contact.queryContactsByEmail('xxx@email.com', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, (err, data) => {
if (err) {
console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`);
......@@ -1089,7 +1111,7 @@ Queries contacts based on the specified email address and attributes. This API u
```js
contact.queryContactsByEmail('xxx@email.com', {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`);
......@@ -1122,9 +1144,11 @@ Queries contacts based on the specified email address, application, and attribut
```js
contact.queryContactsByEmail('xxx@email.com', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryContactsByEmail callback: err->${JSON.stringify(err)}`);
......@@ -1161,9 +1185,11 @@ Queries contacts based on the specified email address, application, and attribut
```js
let promise = contact.queryContactsByEmail('xxx@email.com', {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, {
attributes: ["ATTR_EMAIL", "ATTR_NAME"]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
});
promise.then((data) => {
console.log(`queryContactsByEmail success: data->${JSON.stringify(data)}`);
......@@ -1221,7 +1247,9 @@ Queries all groups of this contact based on the specified application. This API
```js
contact.queryGroups({
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
}, (err, data) => {
if (err) {
console.log(`queryGroups callback: err->${JSON.stringify(err)}`);
......@@ -1256,7 +1284,9 @@ Queries all groups of this contact based on the specified application. This API
```js
let promise = contact.queryGroups({
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
});
promise.then((data) => {
console.log(`queryGroups success: data->${JSON.stringify(data)}`);
......@@ -1371,7 +1401,9 @@ Queries the key of a contact based on the specified contact ID and application.
```js
contact.queryKey(id, {
holderId:1
holderId: 0,
bundleName: "",
displayName: ""
}, (err, data) => {
if (err) {
console.log(`queryKey callback: err->${JSON.stringify(err)}`);
......@@ -1407,7 +1439,9 @@ Queries the key of a contact based on the specified contact ID and application.
```js
let promise = contact.queryKey(id, {
holderId: 0
holderId: 0,
bundleName: "",
displayName: ""
});
promise.then((data) => {
console.log(`queryKey success: data->${JSON.stringify(data)}`);
......
# DataAbilityPredicates
> **NOTE**<br/>
>
> 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.
......@@ -17,7 +18,7 @@ import dataAbility from '@ohos.data.dataAbility';
createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates
Creates an **RdbPredicates** object based on a **DataAbilityPredicates** object.
Creates an **RdbPredicates** object from a **DataAbilityPredicates** object.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
......@@ -69,8 +70,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi")
dataAbilityPredicates.equalTo("NAME", "lisi")
```
......@@ -97,8 +97,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.notEqualTo("NAME", "lisi")
dataAbilityPredicates.notEqualTo("NAME", "lisi")
```
......@@ -119,8 +118,7 @@ Adds a left parenthesis to this **DataAbilityPredicates**.
**Example**
```js
let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi")
dataAbilityPredicates.equalTo("NAME", "lisi")
.beginWrap()
.equalTo("AGE", 18)
.or()
......@@ -146,8 +144,7 @@ Adds a right parenthesis to this **DataAbilityPredicates**.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi")
dataAbilityPredicates.equalTo("NAME", "lisi")
.beginWrap()
.equalTo("AGE", 18)
.or()
......@@ -173,8 +170,7 @@ Adds the OR condition to this **DataAbilityPredicates**.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
dataAbilityPredicates.equalTo("NAME", "Lisa")
.or()
.equalTo("NAME", "Rose")
```
......@@ -197,8 +193,7 @@ Adds the AND condition to this **DataAbilityPredicates**.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
dataAbilityPredicates.equalTo("NAME", "Lisa")
.and()
.equalTo("SALARY", 200.5)
```
......@@ -227,8 +222,7 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.contains("NAME", "os")
dataAbilityPredicates.contains("NAME", "os")
```
......@@ -255,8 +249,7 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.beginsWith("NAME", "os")
dataAbilityPredicates.beginsWith("NAME", "os")
```
......@@ -283,8 +276,7 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe
**Example**
```
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.endsWith("NAME", "se")
dataAbilityPredicates.endsWith("NAME", "se")
```
......@@ -310,8 +302,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.isNull("NAME")
dataAbilityPredicates.isNull("NAME")
```
......@@ -337,8 +328,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.isNotNull("NAME")
dataAbilityPredicates.isNotNull("NAME")
```
......@@ -365,8 +355,7 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.like("NAME", "%os%")
dataAbilityPredicates.like("NAME", "%os%")
```
......@@ -393,8 +382,7 @@ Sets a **DataAbilityPredicates** object to match the specified string.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.glob("NAME", "?h*g")
dataAbilityPredicates.glob("NAME", "?h*g")
```
......@@ -422,8 +410,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.between("AGE", 10, 50)
dataAbilityPredicates.between("AGE", 10, 50)
```
......@@ -451,8 +438,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.notBetween("AGE", 10, 50)
dataAbilityPredicates.notBetween("AGE", 10, 50)
```
......@@ -479,8 +465,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.greaterThan("AGE", 18)
dataAbilityPredicates.greaterThan("AGE", 18)
```
......@@ -507,8 +492,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.lessThan("AGE", 20)
dataAbilityPredicates.lessThan("AGE", 20)
```
......@@ -535,8 +519,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.greaterThanOrEqualTo("AGE", 18)
dataAbilityPredicates.greaterThanOrEqualTo("AGE", 18)
```
......@@ -563,8 +546,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.lessThanOrEqualTo("AGE", 20)
dataAbilityPredicates.lessThanOrEqualTo("AGE", 20)
```
......@@ -590,8 +572,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.orderByAsc("NAME")
dataAbilityPredicates.orderByAsc("NAME")
```
......@@ -617,8 +598,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.orderByDesc("AGE")
dataAbilityPredicates.orderByDesc("AGE")
```
......@@ -639,14 +619,7 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct("NAME")
let promiseDistinct = rdbStore.query(predicates, ["NAME"])
promiseDistinct.then((resultSet) => {
console.log("distinct")
}).catch((err) => {
expect(null).assertFail();
})
dataAbilityPredicates.equalTo("NAME", "Rose").distinct()
```
......@@ -672,8 +645,7 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").limitAs(3)
dataAbilityPredicates.equalTo("NAME", "Rose").limitAs(3)
```
......@@ -699,8 +671,7 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").offsetAs(3)
dataAbilityPredicates.equalTo("NAME", "Rose").offsetAs(3)
```
......@@ -726,8 +697,7 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.groupBy(["AGE", "NAME"])
dataAbilityPredicates.groupBy(["AGE", "NAME"])
```
### indexedBy
......@@ -751,8 +721,7 @@ Sets a **DataAbilityPredicates** object to specify the index column.
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.indexedBy("SALARY_INDEX")
dataAbilityPredicates.indexedBy("SALARY_INDEX")
```
......@@ -780,8 +749,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array<
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.in("AGE", [18, 20])
dataAbilityPredicates.in("AGE", [18, 20])
```
......@@ -809,8 +777,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array<
**Example**
```js
let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE")
predicates.notIn("NAME", ["Lisa", "Rose"])
dataAbilityPredicates.notIn("NAME", ["Lisa", "Rose"])
```
## ValueType
......
......@@ -923,7 +923,7 @@ Enumerates operation types of the Data ability.
**System capability**: SystemCapability.Ability.AbilityBase
| Name | Name | Description |
| Name | Value | Description |
| ------------------------------------ | ---------- | ---------------------------------------- |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. |
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册