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

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

......@@ -20,7 +20,6 @@
- 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)
......
......@@ -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,9 +223,11 @@ 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);
}
```
......@@ -240,16 +235,16 @@ For details about the persistence method, see [Lightweight Data Store Developmen
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 = ''
......
......@@ -166,13 +166,3 @@ The following example shows how to implement a distributed data object synchroni
```js
local_object.setSessionId("");
```
\ No newline at end of file
## 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.
......@@ -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)
# 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.
```
## 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.
```js
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
......@@ -39,10 +42,10 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
var state = audioRenderer.state;
```
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.
```
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) {
......@@ -68,31 +71,33 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
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.
```
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.
```js
await audioCapturer.start();
if (audioCapturer.state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started');
} else {
console.info('AudioRecLog: Capturer start failed');
}
```
4. Obtain the minimum buffer size to read using the **getBufferSize()** API.
```
4. Use **getBufferSize()** to obtain the minimum buffer size to read.
```js
var bufferSize = await audioCapturer.getBufferSize();
console.info('AudioRecLog: buffer size: ' + bufferSize);
```
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.
```
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';
......@@ -123,7 +128,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
numBuffersToCapture--;
}
```
6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording.
6. Once the recording is complete, call **stop()** to stop the recording.
```
await audioCapturer.stop();
if (audioCapturer.state == audio.AudioState.STATE_STOPPED) {
......@@ -133,8 +140,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
}
```
7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources.
```
7. After the task is complete, call **release()** to release related resources.
```js
await audioCapturer.release();
if (audioCapturer.state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released');
......@@ -142,11 +150,3 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
console.info('AudioRecLog: Capturer release 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.
## **Other APIs**
See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**.
# Audio Rendering Development
---
## ***Note***:
1. This document applies to JavaScript.
---
## **Summary**
This guide will show you how to use AudioRenderer to create an audio player app.
You can use the APIs provided in this document to play audio files in output devices and manage playback tasks.
## **AudioRenderer Framework**
The AudioRenderer interface is one of the most important components of the audio framework.
### **Audio Rendering:**
The AudioRenderer framework provides APIs for playing audio files and controlling the playback.
### **Audio Interruption:**
When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\
For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\
With the sample code below, we'll look at how AudioInterrupt works in detail.\
<br/>
Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType.
## **Usage**
Here's an example of how to use AudioRenderer to play a raw audio file.
1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\
This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications.
```
## When to Use
**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks.
### Audio Interruption
When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop).
### State Check
During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior.
**Figure 1** Audio renderer state
![](figures/audio-renderer-state.png)
### Asynchronous Operations
To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
## How to Develop
1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```js
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
......@@ -46,48 +49,15 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
```
2. Subscribe to audio interruption events using the **on** API.\
Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\
In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on.
In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\
<br/>
The following information will be provided by the Interrupt Event Notification:
1) **eventType:** Whether the interruption has begun or ended.
| Value | Description |
| :------------------- | :-------------------------------------------- |
| INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. |
| INTERRUPT_TYPE_END | Indicates that the interruption has finished. |
2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action.
2. Use **on('interrupt')** to subscribe to audio interruption events.
| Value | Description |
| :-------------- | :------------------------------------------------------------------ |
| INTERRUPT_FORCE | The audio state has been changed by the framework. |
| INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. |
Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.
3) **hintType:** The kind of action taken or to be taken.
In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it.
| Value | Description |
| :-------------------- | :--------------------------- |
| INTERRUPT_HINT_PAUSE | Pausing the playback. |
| INTERRUPT_HINT_RESUME | Resuming the playback. |
| INTERRUPT_HINT_STOP | Stopping the playback. |
| INTERRUPT_HINT_DUCK | Ducking the stream volume. |
| INTERRUPT_HINT_UNDUCK | Unducking the stream volume. |
In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9).
4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\
For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback.
| Action | Description |
| :-------------------- | :-------------------------------------------------------------------------------- |
| INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. |
| INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
| INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
```
```js
audioRenderer.on('interrupt', (interruptEvent) => {
console.info('InterruptEvent Received');
console.info('InterruptType: ' + interruptEvent.eventType);
......@@ -133,12 +103,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
});
```
4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\
The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers.
```
3. Use **start()** to start audio rendering.
The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers.
```js
async function startRenderer() {
var state = audioRenderer.state;
// state should be prepared, paused or stopped.
// The state should be prepared, paused, or stopped.
if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED ||
state != audio.AudioState.STATE_STOPPED) {
console.info('Renderer is not in a correct state to start');
......@@ -154,11 +126,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
console.error('Renderer start failed');
}
}
```
5. Make **write** calls to start rendering the buffers.
Read the audio data to be played into a buffer. Call the write function repeatedly to write data.
```
4. Call **write()** to write data to the buffer.
Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer.
```js
async function writeBuffer(buf) {
var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) {
......@@ -201,8 +175,9 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} , 30); // interval to be set based on audio file format
```
6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance.
```
5. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
```js
async function pauseRenderer() {
var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) {
......@@ -235,12 +210,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} else {
console.error('Renderer stop failed');
}
}
```
}
```
7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\
AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**.
```
6. After the task is complete, call **release()** to release related resources.
**AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete.
```js
async function releaseRenderer() {
if (state_ == RELEASED || state_ == NEW) {
console.info('Resourced already released');
......@@ -257,18 +234,6 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
}
}
```
## **Importance of State Check:**
You should also keep in mind that an AudioRenderer is state-based.
That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\
The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\
```
## **Asynchronous Operations:**
Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\
For each API, the framework provides both callback and promises functions.\
In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8)
provides reference for both callback and promise.
## **Other APIs:**
See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize.
# 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/>
> **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.|
| 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/>
> **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
>![](../../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.
> **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.
## Modules to Import
**requestAnimationFrame**: none
**cancelAnimationFrame**: none
**createAnimator**:
## Modules to Import
```
import animator from '@ohos.animator';
```
## Required Permissions
None
## requestAnimationFrame
requestAnimationFrame\(handler\[, \[ ...args\]\]\): number
Requests an animation frame.
- Parameters
| 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. |
- Return values
| Type | Description |
| ------ | ----------- |
| number | Request ID. |
- Example
```
<!-- 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);
}
}
}
```
## cancelAnimationFrame
cancelAnimationFrame\(requestId: number\): void
Cancels the animation frame request.
- Parameters
| Name | Type | Mandatory | Description |
| --------- | ------ | --------- | ------------------------ |
| requestId | number | Yes | ID of the frame request. |
- Example
```
<!-- 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);
}
}
```
## createAnimator
createAnimator\(options\[...\]\): void
Creates an animation object.
- Parameters
createAnimator(options: AnimatorOptions): AnimatorResult
| Name | Type | Mandatory | Description |
| ------- | ------ | --------- | ------------------------------------------------------------ |
| options | Object | Yes | Attributes of the **Animator** to be created. For details, see the options table. |
Creates an **Animator** object.
- Description of options
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| 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. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.|
- animator interfaces
**Return value**
| Type| Description|
| -------- | -------- |
| [AnimatorResult](#animatorresult) | Animator result.|
| 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
**Example**
```
<!-- hml -->
......@@ -246,3 +77,164 @@ Creates an animation object.
}
}
```
## AnimatorResult
Defines the animator result.
### update
update(options: AnimatorOptions): void
Updates this animator.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.|
**Example**
```
animator.update(options);
```
### play
play(): void
Plays this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.play();
```
### finish
finish(): void
Ends this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.finish();
```
### pause
pause(): void
Pauses this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.pause();
```
### cancel
cancel(): void
Cancels this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**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/>
> **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>
> **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
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();
console.log("stage applicationContext: " + JSON.stringify(applicationContext));
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
......
# Preferences
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and supports lightweight data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type.
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type.
> **NOTE**<br/>
......@@ -19,8 +19,8 @@ import data_preferences from '@ohos.data.preferences';
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It is 80 bytes.|
| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It is 8192 bytes.|
| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.|
| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.|
## data_preferences.getPreferences
......@@ -33,11 +33,11 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes| Callback used to return the result.|
**Example**
```ts
......@@ -60,15 +60,15 @@ Reads a **Preferences** persistence file and loads data to the **Preferences** i
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -91,11 +91,11 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
......@@ -119,15 +119,15 @@ Once a **Preferences** persistence file is deleted, the **Preferences** instance
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -151,11 +151,11 @@ When a **Preferences** singleton instance is removed, this instance cannot be us
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
......@@ -179,16 +179,16 @@ When a **Preferences** singleton instance is removed, this instance cannot be us
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [Context](js-apis-ability-context.md) | Yes| Context of the application or functionality.|
| name | string | Yes| Name of the **Preferences** instance persistence file.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -215,15 +215,15 @@ Obtains the value of a key. If the value is null or a non-default value, the def
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to obtain. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;ValueType&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to obtain. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;ValueType&gt; | Yes| Callback used to return the result.|
**Example**
```ts
preferences.get('startup', 'default', function(err, value) {
preferences.get('startup', 'default', function(err, value) {
if (err) {
console.info("Failed to get the value of startup, err: " + err)
return
......@@ -242,15 +242,15 @@ Obtains the value of a key. If the value is null or a non-default value, the def
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to obtain. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to obtain. It cannot be empty.|
| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;ValueType&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;ValueType&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -262,6 +262,57 @@ promise.then((value) => {
})
```
### getAll
getAll(callback: AsyncCallback&lt;Object&gt;): void;
Obtains the **Object** instance that contains all KV pairs.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Object&gt; | Yes| Callback used to return the **Object** instance obtained.|
**Example**
```ts
preferences.get.getAll(function (err, value) {
if (err) {
console.info("getAll failed, err: " + err)
return
}
let keys = Object.keys(value)
console.info('getAll keys = ' + keys)
console.info("getAll object = " + JSON.stringify(value))
});
```
### getAll
getAll(): Promise&lt;Object&gt;
Obtains the **Object** instance that contains all KV pairs.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Object&gt; | Promise used to return the **Object** instance obtained.|
**Example**
```ts
let promise = preferences.getAll()
promise.then((value) => {
let keys = Object.keys(value)
console.info('getAll keys = ' + keys)
console.info("getAll object = " + JSON.stringify(value))
}).catch((err) => {
console.info("getAll failed, err: " + err)
})
```
### put
......@@ -272,11 +323,11 @@ Puts a new value to this **Preferences** instance and its persistence file. This
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
......@@ -299,15 +350,15 @@ Puts a new value to this **Preferences** instance and its persistence file. This
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -322,22 +373,17 @@ promise.then(() => {
### has
has(key: string, callback: AsyncCallback&lt;boolean&gt;): boolean
has(key: string, callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this **Preferences** instance contains data with a given key. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to check. It cannot be empty.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the **Preferences** instance contains data with the specified key; returns **false** otherwise.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to check. It cannot be empty.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.|
**Example**
```ts
......@@ -364,14 +410,14 @@ Checks whether this **Preferences** instance contains data with a given key. Thi
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to check. It cannot be empty.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to check. It cannot be empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.|
**Example**
```ts
......@@ -383,7 +429,7 @@ promise.then((isExist) => {
console.info("The key of startup is not contained.")
}
}).catch((err) => {
console.info("Check the key of startup failed, err: " + err)
console.info("Failed to check the key of startup, err: " + err)
})
```
......@@ -397,10 +443,10 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the KV pair to delete. It cannot be empty.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the KV pair to delete. It cannot be empty.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
......@@ -423,14 +469,14 @@ Deletes a KV pair of the specified key from this **Preferences** instance. This
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the KV pair to delete. It cannot be empty.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the KV pair to delete. It cannot be empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -452,9 +498,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
......@@ -477,9 +523,9 @@ Saves the modification to this **Preferences** instance and synchronizes the mod
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -500,10 +546,10 @@ Clears data of this **Preferences** instance. This API uses an asynchronous call
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```ts
......@@ -526,9 +572,9 @@ Clears data of this **Preferences** instance. This API uses a promise to return
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```ts
......@@ -550,10 +596,10 @@ Subscribes to data changes. When the value of the subscribed key changes, a call
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Description|
| -------- | -------- | -------- |
| type | string | Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | Callback used to return data changes.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | Yes| Callback used to return data changes.|
**Example**
```ts
......@@ -584,17 +630,17 @@ preferences.put('startup', 'auto', function (err) {
### off('change')
off(type: 'change', callback: Callback&lt;{ key : string }&gt;): void
off(type: 'change', callback?: Callback&lt;{ key : string }&gt;): void
Unsubscribes from data changes.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name| Type| Description|
| -------- | -------- | -------- |
| type | string | Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | Callback used to return data changes.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.|
**Example**
```ts
......
......@@ -22,15 +22,15 @@ import dataStorage from '@ohos.data.storage';
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It is 80 bytes.|
| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It is 8192 bytes.|
| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.|
| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.|
## dataStorage.getStorageSync
getStorageSync(path: string): Storage
Reads the specified file and load its data to the **Storage** instance for data operations.
Reads the specified file and loads its data to the **Storage** instance for data operations.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
......
# Device Information
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **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.
## Modules to Import
......@@ -24,7 +24,7 @@ import deviceInfo from '@ohos.deviceInfo'
| softwareModel | string | Yes| No| Software model.|
| hardwareModel | string | Yes| No| Hardware model.|
| hardwareProfile | string | Yes| No| Hardware profile.|
| serial | string | Yes| No| Device serial number.|
| serial | string | Yes| No| Device serial number.<br>**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)|
| bootloaderVersion | string | Yes| No| Bootloader version.|
| abiList | string | Yes| No| Application binary interface (Abi) list.|
| securityPatchTag | string | Yes| No| Security patch tag.|
......@@ -44,4 +44,4 @@ import deviceInfo from '@ohos.deviceInfo'
| buildHost | string | Yes| No| Build host.|
| buildTime | string | Yes| No| Build time.|
| buildRootHash | string | Yes| No| Build root hash.|
| udid<sup>7+</sup> | string | Yes| No| Device UDID.|
| udid<sup>7+</sup> | string | Yes| No| Device UDID.<br>**Required permissions**: ohos.permission.sec.ACCESS_UDID (a system permission)|
......@@ -11,11 +11,11 @@ import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager';
```
## enterpriseDeviceManager.activateAdmin
## enterpriseDeviceManager.enableAdmin
activateAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\<boolean>): void
enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number, callback: AsyncCallback\<boolean>): void
Activates a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result.
Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result.
**Required permissions**
......@@ -27,12 +27,13 @@ SystemCapability.Customation.EnterpriseDeviceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. |
| type | [AdminType](#AdminType) | Yes | Type of the device administrator to activate. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. |
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. |
| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. |
| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. |
**Example**
......@@ -45,7 +46,7 @@ let enterpriseInfo = {
name: "enterprise name",
description: "enterprise description"
}
enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, (error, result) => {
enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100, (error, result) => {
if (error != null) {
console.log("error occurs" + error);
return;
......@@ -54,11 +55,11 @@ enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDevice
});
```
## enterpriseDeviceManager.activateAdmin
## enterpriseDeviceManager.enableAdmin
activateAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType): Promise\<boolean>
enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number): Promise\<boolean>
Activates a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result.
Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result.
**Required permissions**
......@@ -70,11 +71,12 @@ SystemCapability.Customation.EnterpriseDeviceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | ---------------------------------------------- | ---- | ------------------------ |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. |
| type | [AdminType](#AdminType) | Yes | Type of the device administrator to activate. |
| Name | Type | Mandatory | Description |
| -------------- | ---------------------------------------------- | ---- | ------------------------ |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. |
| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. |
| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. |
**Return value**
......@@ -93,7 +95,7 @@ let enterpriseInfo = {
name: "enterprise name",
description: "enterprise description"
}
enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL)
enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100)
.then((result) => {
console.log(result);
}).catch(error => {
......@@ -101,11 +103,11 @@ enterpriseDeviceManager.activateAdmin(wantTemp, enterpriseInfo, enterpriseDevice
});
```
## enterpriseDeviceManager.deactivateAdmin
## enterpriseDeviceManager.disableAdmin
deactivateAdmin(admin: Want, callback: AsyncCallback\<boolean>): void
disableAdmin(admin: Want, userId?: number, callback: AsyncCallback\<boolean>): void
Deactivates a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result.
Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result.
**Required permissions**
......@@ -117,10 +119,11 @@ SystemCapability.Customation.EnterpriseDeviceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------------- | ---- | ------------------------------ |
| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. |
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------------- | ---- | ------------------------------ |
| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. |
| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. |
**Example**
......@@ -129,7 +132,7 @@ let wantTemp = {
bundleName: elementName.bundleName,
abilityName: elementName.abilityName,
};
enterpriseDeviceManager.deactivateAdmin(wantTemp, (error, result) => {
enterpriseDeviceManager.disableAdmin(wantTemp, 100, (error, result) => {
if (error != null) {
console.log("error occurs" + error);
return;
......@@ -140,11 +143,11 @@ enterpriseDeviceManager.deactivateAdmin(wantTemp, (error, result) => {
## enterpriseDeviceManager.deactivateAdmin
## enterpriseDeviceManager.disableAdmin
deactivateAdmin(admin: Want): Promise\<boolean>
disableAdmin(admin: Want, userId?: number): Promise\<boolean>
Deactivates a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result.
Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result.
**Required permissions**
......@@ -156,9 +159,10 @@ SystemCapability.Customation.EnterpriseDeviceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ---------------------------------------------- | ---- | ------------------ |
| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. |
| Name | Type | Mandatory | Description |
| ------ | ---------------------------------------------- | ---- | ------------------ |
| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. |
| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. |
**Return value**
......@@ -173,18 +177,18 @@ let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
enterpriseDeviceManager.deactivateAdmin(wantTemp).then((result) => {
enterpriseDeviceManager.disableAdmin(wantTemp, 100).then((result) => {
console.log(result);
}).catch(error => {
console.log("error occurs" + error);
});
```
## enterpriseDeviceManager.deactivateSuperAdmin
## enterpriseDeviceManager.disableSuperAdmin
deactivateSuperAdmin(bundleName: String, callback: AsyncCallback\<boolean>): void
disableSuperAdmin(bundleName: String, callback: AsyncCallback\<boolean>): void
Deactivates a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result.
Disables a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result.
**System capability**
......@@ -201,7 +205,7 @@ SystemCapability.Customation.EnterpriseDeviceManager
```
let bundleName = "com.example.myapplication";
enterpriseDeviceManager.deactivateSuperAdmin(bundleName, (error, result) => {
enterpriseDeviceManager.disableSuperAdmin(bundleName, (error, result) => {
if (error != null) {
console.log("error occurs" + error);
return;
......@@ -210,11 +214,11 @@ enterpriseDeviceManager.deactivateSuperAdmin(bundleName, (error, result) => {
});
```
## enterpriseDeviceManager.deactivateSuperAdmin
## enterpriseDeviceManager.disableSuperAdmin
deactivateSuperAdmin(bundleName: String): Promise\<boolean>
disableSuperAdmin(bundleName: String): Promise\<boolean>
Deactivates a device super administrator application based on the specified bundle name. This API uses a promise to return the result.
Disables a device super administrator application based on the specified bundle name. This API uses a promise to return the result.
**System capability**
......@@ -236,18 +240,18 @@ SystemCapability.Customation.EnterpriseDeviceManager
```
let bundleName = "com.example.myapplication";
enterpriseDeviceManager.deactivateSuperAdmin(bundleName).then((result) => {
enterpriseDeviceManager.disableSuperAdmin(bundleName).then((result) => {
console.log(result);
}).catch(error => {
console.log("error occurs" + error);
});
```
## enterpriseDeviceManager.isAdminAppActive
## enterpriseDeviceManager.isAdminEnabled
isAdminAppActive(admin: Want, callback: AsyncCallback\<boolean>): void
isAdminEnabled(admin: Want, userId?: number, callback: AsyncCallback\<boolean>): void
Checks whether a device administrator application is activated based on the specified bundle name and class name. This API uses an asynchronous callback to return the result.
Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result.
**System capability**
......@@ -255,10 +259,11 @@ SystemCapability.Customation.EnterpriseDeviceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------------- | ---- | -------------------------------- |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. |
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------------- | ---- | -------------------------------- |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. |
**Example**
......@@ -267,7 +272,7 @@ let wantTemp = {
bundleName: elementName.bundleName,
abilityName: elementName.abilityName,
};
enterpriseDeviceManager.isAdminAppActive(wantTemp, (error, result) => {
enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => {
if (error != null) {
console.log("error occurs" + error);
return;
......@@ -278,11 +283,11 @@ enterpriseDeviceManager.isAdminAppActive(wantTemp, (error, result) => {
## enterpriseDeviceManager.isAdminAppActive
## enterpriseDeviceManager.isAdminEnabled
isAdminAppActive(admin: Want): Promise\<boolean>
isAdminEnabled(admin: Want, userId?: number): Promise\<boolean>
Checks whether a device administrator application is activated based on the specified bundle name and class name. This API uses a promise to return the result.
Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses a promise to return the result.
**System capability**
......@@ -290,9 +295,10 @@ SystemCapability.Customation.EnterpriseDeviceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ---------------------------------------------- | ---- | -------------- |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| Name | Type | Mandatory | Description |
| ------ | ---------------------------------------------- | ---- | -------------- |
| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. |
| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. |
**Return value**
......@@ -307,7 +313,7 @@ let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
enterpriseDeviceManager.isAdminAppActive(wantTemp).then((result) => {
enterpriseDeviceManager.isAdminEnabled(wantTemp, 100).then((result) => {
console.log(result);
}).catch(error => {
console.log("error occurs" + error);
......@@ -318,7 +324,7 @@ enterpriseDeviceManager.isAdminAppActive(wantTemp).then((result) => {
isSuperAdmin(bundleName: String, callback: AsyncCallback\<boolean>): void
Checks whether a device super administrator application is activated based on the specified bundle name. This API uses an asynchronous callback to return the result.
Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result.
**System capability**
......@@ -350,7 +356,7 @@ enterpriseDeviceManager.isSuperAdmin(bundleName, (error, result) => {
isSuperAdmin(bundleName: String): Promise\<boolean>
Checks whether a device super administrator application is activated based on the specified bundle name. This API uses a promise to return the result.
Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses a promise to return the result.
**System capability**
......
......@@ -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. |
......
......@@ -21,7 +21,7 @@ None
| Name | Type | Readable| Writable| Description |
| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- |
| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This class is inherited from **ExtensionContext**.|
| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.|
## onCreate
......@@ -227,7 +227,7 @@ Called when the configuration of the environment where the ability is running is
onAcquireFormState?(want: Want): formInfo.FormState;
Used by the widget provider to receive the widget state query request. By default, the initial widget state is returned.
Called when the widget provider receives the status query result of a specified service widget. By default, the initial state is returned.
**System capability**: SystemCapability.Ability.Form
......
# HiLog
The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs.
This document describes only API functions. For details about log printing requirements, see [Logging Guide](../../../contribute/OpenHarmony-Log-guide.md).
> **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.
......
此差异已折叠。
......@@ -36,7 +36,7 @@ Enables listening for hot swap events of an input device.
let isPhysicalKeyboardExist = true;
inputDevice.on("change", (data) => {
console.log("type: " + data.type + ", deviceId: " + data.deviceId);
inputDevice.getKeyboardType(data.deviceId, (ret) => {
inputDevice.getKeyboardType(data.deviceId, (err, ret) => {
console.log("The keyboard type of the device is: " + ret);
if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is connected.
......@@ -68,12 +68,12 @@ Disables listening for hot swap events of an input device.
**Example**
```js
listener: function(data) {
function listener(data) {
console.log("type: " + data.type + ", deviceId: " + data.deviceId);
}
// Disable this listener.
inputDevice.off("change", this.listener);
inputDevice.off("change", listener);
// Disable all listeners.
inputDevice.off("change");
......@@ -104,7 +104,7 @@ inputDevice.getDeviceIds((ids)=>{
## inputDevice.getDeviceIds
function getDeviceIds(): Promise&lt;&lt;Array&lt;number&gt;&gt;
getDeviceIds(): Promise&lt;Array&lt;number&gt;&gt;
Obtains the IDs of all input devices. This API uses a promise to return the result.
......@@ -150,7 +150,7 @@ inputDevice.getDevice(1, (inputDevice)=>{
## inputDevice.getDevice
function getDevice(deviceId: number): Promise&lt;InputDeviceData&gt;
getDevice(deviceId: number): Promise&lt;InputDeviceData&gt;
Obtains information about an input device. This API uses a promise to return the result.
......@@ -336,7 +336,7 @@ Defines the axis range of an input device.
| Name | Type | Description |
| ----------------------- | ------------------------- | -------- |
| source | [SourceType](#sourcetype) | Input source type of the axis.|
| axis | [AxisType](axistype) | Axis type. |
| axis | [AxisType](#axistype) | Axis type. |
| max | number | Maximum value of the axis. |
| min | number | Minimum value of the axis. |
| fuzz<sup>9+</sup> | number | Fuzzy value of the axis. |
......
# Input Method Framework
> ![icon-note.gif](public_sys-resources/icon-note.gif) **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**<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.
>
......@@ -48,9 +48,9 @@ Obtains an [InputMethodController](#InputMethodController) instance.
**Example**
```
var InputMethodController = inputMethod.getInputMethodController();
```
```js
var InputMethodController = inputMethod.getInputMethodController();
```
## inputMethod.getInputMethodSetting<sup>8+</sup><a name="getInputMethodSetting"></a>
......@@ -140,18 +140,18 @@ Obtains the list of installed input methods. This API uses an asynchronous callb
**Example**
```js
```js
InputMethodSetting.listInputMethod((properties)=>{
for (var i = 0;i < properties.length; i++) {
var property = properties[i];
console.info(property.packageName + "/" + property.methodId);
}
});
```
});
```
### listInputMethod
listInputMethod(): Array&lt;InputMethodProperty&gt;
listInputMethod(): Promise&lt;Array&lt;InputMethodProperty&gt;&gt;
Obtains the list of installed input methods. This API uses an asynchronous callback to return the result.
......
# Media Library Management
# MediaLibrary
> **NOTE**<br>
> **NOTE**
>
> This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -93,7 +94,7 @@ let imagesfetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
};
mediaLibrary.getFileAssets(imagesfetchOp, (error, fetchFileResult) => {
media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => {
if (fetchFileResult != undefined) {
console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success');
fetchFileResult.getAllObject((err, fileAssetList) => {
......@@ -135,7 +136,7 @@ let imagesfetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
};
mediaLibrary.getFileAssets(imagesfetchOp).then(function(fetchFileResult){
media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){
console.info("getFileAssets successfully:"+ JSON.stringify(dir));
}).catch(function(err){
console.info("getFileAssets failed with error:"+ err);
......@@ -182,7 +183,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb
**Example**
```
mediaLibrary.off('imageChange', () => {
media.off('imageChange', () => {
// stop listening success
})
```
......@@ -350,7 +351,7 @@ let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
mediaLibrary.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => {
media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => {
if (albumList != undefined) {
const album = albumList[0];
console.info('album.albumName = ' + album.albumName);
......@@ -390,7 +391,7 @@ let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
mediaLibrary.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){
media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){
console.info("getAlbums successfully:"+ JSON.stringify(albumList));
}).catch(function(err){
console.info("getAlbums failed with error:"+ err);
......@@ -439,7 +440,6 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in
**Example**
```
var media = mediaLibrary.getMediaLibrary(context);
media.release()
```
......@@ -1957,7 +1957,7 @@ async function example() {
Provides APIs to implement a physical album.
### **Attributes**
### Attributes
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core
......
......@@ -408,7 +408,7 @@ Checks whether the current device supports 5G \(NR\).
```js
let slotId = 0;
let result = radio.isNrSupported(slotId);
console.log(result);
console.log("Result: "+ result);
```
......
......@@ -521,7 +521,7 @@ Obtains the number of card slots.
**Example**
```js
console.log(sim.getMaxSimCount())
console.log("Result: "+ sim.getMaxSimCount())
```
......
......@@ -68,7 +68,7 @@ Sets the value in the cache based on the specified key.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to set.|
| value | string | Yes| New value to set. The maximum length is 128 bytes.|
| value | string | Yes| New value to set. The length must be less than 128 bytes.|
| success | Function | No| Called when **storage.set()** is successful.|
| fail | Function | No| Called when **storage.set()** fails. In the callback, **data** indicates the error information, and **code** indicates the error code.|
| complete | Function | No| Called when **storage.set()** is complete.|
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册