提交 d432ed78 编写于 作者: S shawn_he 提交者: Gitee

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

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
......@@ -16,8 +16,8 @@ The following table lists the common APIs for input device management. For detai
| Instance| API | Description|
| ----------- | ------------------------------------------------------------ | -------------------------- |
| inputDevice | function getDeviceList(callback: AsyncCallback\<Array\<number>>): void; | Obtains the list of input devices.|
| inputDevice | function getKeyboardType(deviceId: number, callback: AsyncCallback\<KeyboardType>): void; | Obtains the keyboard type of the input device.|
| inputDevice | function getDeviceList(): Promise\<Array\<number>>; | Obtains the list of input devices.|
| inputDevice | function getKeyboardType(deviceId: number): Promise\<KeyboardType>; | Obtains the keyboard type of the input device.|
| inputDevice | function on(type: "change", listener: Callback\<DeviceListener>): void; | Enables listening for device hot swap events.|
| inputDevice | function off(type: "change", listener?: Callback\<DeviceListener>): void; | Disables listening for device hot swap events.|
......@@ -51,7 +51,7 @@ try {
// 2. Listen for device hot swap events.
inputDevice.on("change", (data) => {
console.log(`Device event info: ${JSON.stringify(data)}`);
inputDevice.getKeyboardType(data.deviceId, (error, type) => {
inputDevice.getKeyboardType(data.deviceId).then((type) => {
console.log("The keyboard type is: " + type);
if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is inserted.
......
# Common Event and Notification
# Notification
- [Notification Overview](notification-overview.md)
- [Notification Subscription (Open Only to System Applications)](notification-subscription.md)
- [Enabling Notification](notification-enable.md)
- Publishing a Notification
- [Publishing a Basic Notification](text-notification.md)
- [Publishing a Progress Notification](progress-bar-notification.md)
- [Adding a WantAgent Object to a Notification](notification-with-wantagent.md)
- [Common Event and Notification Overview](notification-brief.md)
- [Common Event Development](common-event.md)
- [Notification Development](notification-guidelines.md)
- Agent-Powered Scheduled Reminder
- [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md)
- [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md)
- [Debugging Assistant Usage](assistant-guidelines.md)
# Debugging Assistant Usage
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
### publish
* Function
Publishes a common event.
* Usage
`cem publish [<options>]`
The table below describes the available options.
| Option | Description |
| ------------ | ------------------------------------------ |
| -e/--event | Indicates the name of the common event to publish. Mandatory. |
| -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published. |
| -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. |
| -c/--code | Indicates the result code of the common event. Optional. |
| -d/--data | Indicates the data carried in the common event. Optional. |
| -h/--help | Indicates the help Information |
* Example
`cem publish --event "testevent"`
Publish a common event named **testevent**.
![cem-publish-event](figures/cem-publish-event.png)
`cem publish -e "testevent" -s -o -c 100 -d "this is data" `
Publish a sticky, ordered common event named **testevent**. The result code of the event is **100** and the data carried is **this is data**.
![cem-publish-all](figures/cem-publish-all.png)
### dump
* Function
Displays information about common events.
* Usage
`cem dump [<options>]`
The table below describes the available options.
| Option | Description |
| ---------- | -------------------------------------------- |
| -a/--all | Displays information about all common events that have been sent since system startup. |
| -e/--event | Displays information about a specific event. |
| -h/--help | Displays the help information. |
* Example
`cem dump -e "testevent"`
​ Display information about the common event testevent.
​ ![cem-dump-e](figures/cem-dump-e.png)
### help
* Function
Displays the help information.
* Usage
`cem help`
* Example
![cem-help](figures/cem-help.png)
## anm Debugging Assistant
### dump
* Function
Displays information about notifications.
* Usage
`anm dump [<options>]`
The table below describes the available options.
| Option | Description |
| ---------------- | ---------------------------------------- |
| -A/--active | Displays information about all active notifications. |
| -R/--recent | Displays information about the recent notifications. |
| -D/--distributed | Displays information about distributed notifications from other devices. |
| --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional. |
| -h/--help | Displays the help information. |
* Example
`anm dump -A`
Display information about all active notifications.
![anm-dump-A](figures/anm-dump-A.png)
`anm dump --setRecentCount 10`
Set the number of the cached recent notifications to be displayed to **10**.
### help
* Function
Displays the help information.
* Usage
`anm help`
* Example
![anm-help](figures/anm-help.png)
# Common Event Development
## 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.
+ System common events: The system sends an event based on system policies to the apps that have subscribed to this event when it occurs. This type of event is typically system events published by key system services, such as HAP installation, update, and uninstallation.
+ Custom common event: customized by applications to implement cross-application event communication.
Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application.
## Common Event Subscription Development
### When to Use
You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#support).
### Available APIs
| API | Description|
| ---------------------------------------------------------------------------------------------- | ----------- |
| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.|
| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. |
| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.|
### How to Develop
1. Import the **commonEvent** module.
```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).
```js
// Used to save the created subscriber object for subsequent subscription and unsubscription.
private subscriber = null
// Subscriber information
var subscribeInfo = {
events: ["event"],
}
```
3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription.
```js
// Callback for subscriber creation.
commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
if (err.code) {
console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err))
} else {
console.log("[CommonEvent]CreateSubscriber")
this.subscriber = subscriber
this.result = "Create subscriber succeed"
}
})
```
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).
```js
// Callback for common event subscription.
if (this.subscriber != null) {
commonEvent.subscribe(this.subscriber, (err, data) => {
if (err.code) {
console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err))
} else {
console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data))
this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code
}
})
this.result = "Subscribe succeed"
} else {
prompt.showToast({ message: "Need create subscriber" })
}
```
## 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.
### Available APIs
| API | Description|
| ---------------------------------- | ------ |
| publish(event: string, callback: AsyncCallback) | Publishes a common event.|
| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.|
### How to Develop
#### Development for Publishing a Common Event
1. Import the **commonEvent** module.
```js
import commonEvent from '@ohos.commonEvent';
```
2. Pass in the common event name and callback, and publish the event.
```js
// Publish a common event.
commonEvent.publish("event", (err) => {
if (err.code) {
console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
} else {
console.info("[CommonEvent]Publish1")
}
})
```
#### Development for Publishing a Common Event with Given Attributes
1. Import the **commonEvent** module.
```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).
```js
// Attributes of a common event.
var options = {
code: 1, // Result code of the common event
data: "initial data";// Result data of the common event
}
```
3. Pass in the common event name, attributes of the common event, and callback, and publish the event.
```js
// Publish a common event.
commonEvent.publish("event", options, (err) => {
if (err.code) {
console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
} else {
console.info("[CommonEvent]Publish2")
}
})
```
## Common Event Unsubscription Development
### When to Use
You can use the **unsubscribe** API to unsubscribe from a common event.
### Available APIs
| API | Description|
| ---------------------------------- | ------ |
| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.|
### How to Develop
1. Import the **commonEvent** module.
```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.
```js
if (this.subscriber != null) {
commonEvent.unsubscribe(this.subscriber, (err) => {
if (err.code) {
console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err))
} else {
console.log("[CommonEvent]Unsubscribe")
this.subscriber = null
this.result = "Unsubscribe succeed"
}
})
}
```
# Common Event and Notification Overview
The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more.
Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events.
![ces](figures/ces.png)
- System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events.
- Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications.
The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications:
- Display received SMS messages and instant messages.
- Display push messages of applications, such as advertisements, version updates, and news notifications.
- Display ongoing events, such as music playback, navigation information, and download progress.
Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions.
![ans](figures/ans.png)
# Enabling Notification
To publish a notification, you must have notification enabled for your application. You can call the [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) API to display a dialog box prompting the user to enable notification for your application. Note that the dialog box is displayed only when the API is called for the first time.
**Figure 1** Dialog box prompting the user to enable notification
![en-us_image_0000001416585590](figures/en-us_image_0000001416585590.png)
- Touching **allow** enables notification for the application, and touching **ban** keeps notification disabled.
- The dialog box will not be displayed again when [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) is called later. The user can manually enable notification as follows.
| 1. Swipe down from the upper left corner of the device screen to access the notification panel. | 2. Touch the **Settings** icon in the upper right corner. On the notification screen, locate the target application.| 3. Toggle on **Allow notifications**. |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ![en-us_image_0000001417062434](figures/en-us_image_0000001417062434.png) | ![en-us_image_0000001466462297](figures/en-us_image_0000001466462297.png) | ![en-us_image_0000001466782025](figures/en-us_image_0000001466782025.png) |
## Available APIs
For details about the APIs, see [@ohos.notificationManager](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification).
**Table 1** Notification APIs
| Name | Description |
| -------- | -------- |
| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether notification is enabled.<br>**NOTE**<br>This is a system API and cannot be called by third-party applications. |
| setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback&lt;void&gt;): void | Sets whether to enable notification. Notification can be enabled or disabled in **Notifications** of the target application under **Settings** > **Apps & services** > **Apps**.<br>**NOTE**<br>This is a system API and cannot be called by third-party applications.|
| requestEnableNotification(callback: AsyncCallback&lt;void&gt;): void | Requests notification to be enabled. When called for the first time, this API displays a dialog box prompting the user to enable notification. |
## How to Develop
1. Import the **NotificationManager** module.
```ts
import notificationManager from '@ohos.notificationManager';
```
2. Call the API to request notification to be enabled.
```ts
notificationManager.requestEnableNotification().then(() => {
console.info(`[ANS] requestEnableNotification success`);
}).catch((err) => {
console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`);
});
```
# Notification Development
## When to Use
OpenHarmony uses the Advanced Notification Service (ANS) to manage notifications, with support for various notification types, including text, long text, multi-text, image, social, and media. All system services and applications can send notifications through the notification API. Users can view all notifications on the system UI.
Below are some typical use cases for notifications:
- Display received SMS messages and instant messages.
- Display push messages of applications, such as advertisements and version updates.
- Display ongoing events, such as navigation information and download progress.
## Notification Service Process
The notification service process involves the ANS subsystem, notification sender, and notification subscriber.
A notification is generated by the notification sender and sent to the ANS through inter-process communication (IPC). The ANS then distributes the notification to the notification subscriber.
System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the ANS for storage in the memory and database.
![1648113187545](figures/notification.png)
## Available APIs
Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md).
**Table 1** APIs for notification enabling
| API | Description |
| ------------------------------------------------------------ | ---------------- |
| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\<boolean>): void | Checks whether notification is enabled.|
| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\<void>): void | Sets whether to enable notification. |
If the notification function of an application is disabled, it cannot send notifications.
**Table 2** APIs for notification subscription
| API | Description |
| ------------------------------------------------------------ | ---------------- |
| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\<void>): void | Subscribes to a notification with the subscription information specified.|
| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Subscribes to all notifications. |
| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Unsubscribes from a notification. |
The subscription APIs support subscription to all notifications and notifications from specific applications.
**Table 3** Notification subscription callbacks
| API | Description |
| ------------------------------------------------ | ---------------- |
| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. |
| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. |
| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.|
| onConnect?:() => void; | Callback for subscription. |
| onDisconnect?:() => void; | Callback for unsubscription. |
**Table 4** APIs for notification sending
| API | Description |
| ------------------------------------------------------------ | ------------------------ |
| publish(request: NotificationRequest, callback: AsyncCallback\<void>): void | Publishes a notification. |
| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\<void>): void | Publishes a notification to the specified user. |
| cancel(id: number, label: string, callback: AsyncCallback\<void>): void | Cancels a specified notification. |
| cancelAll(callback: AsyncCallback\<void>): void; | Cancels all notifications published by the application.|
The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user.
## Development Guidelines
The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications.
### Modules to Import
```js
import Notification from '@ohos.notification';
```
### Subscribing to Notifications
The notification recipient preferentially initiates a notification subscription request to the notification subsystem.
```js
var subscriber = {
onConsume: function (data) {
let req = data.request;
console.info('===>onConsume callback req.id: ' + req.id);
},
onCancel: function (data) {
let req = data.request;
console.info('===>onCancel callback req.id: : ' + req.id);
},
onUpdate: function (data) {
console.info('===>onUpdate in test===>');
},
onConnect: function () {
console.info('===>onConnect in test===>');
},
onDisconnect: function () {
console.info('===>onDisConnect in test===>');
},
onDestroy: function () {
console.info('===>onDestroy in test===>');
},
};
Notification.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result.
if (err.code) {
console.error('===>failed to subscribe because ' + JSON.stringify(err));
return;
}
console.info('===>subscribeTest success : ' + JSON.stringify(data));
});
```
### Publishing Notifications
##### Enabling Notification
Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature.
```js
Notification.requestEnableNotification().then((data) => {
console.info('===>requestEnableNotification success');
}).catch((err) => {
console.error('===>requestEnableNotification failed because ' + JSON.stringify(err));
});
```
##### Publishing Notifications
To publish a notification, create a **NotificationRequest** object and set attributes such as the notification type, title, and content. In the following examples, a normal text notification and a notification containing a **WantAgent** are being published.
Normal text notification:
```js
// Create a NotificationRequest object.
var notificationRequest = {
id: 1,
content: {
contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "test_title",
text: "test_text",
additionalText: "test_additionalText"
}
}
}
// Publish the notification.
Notification.publish(notificationRequest).then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err));
});
```
Notification containing **WantAgent**:
For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md).
- Create a **WantAgent** object.
```js
import wantAgent from '@ohos.wantAgent';
// WantAgentInfo object
var wantAgentInfo = {
wants: [
{
bundleName: 'ohos.samples.eTSNotification',
abilityName: 'ohos.samples.eTSNotification.MainAbility',
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
// WantAgent object
var WantAgent;
// getWantAgent callback
function getWantAgentCallback(err, data) {
console.info("===>getWantAgentCallback===>");
if (err.code == 0) {
WantAgent = data;
} else {
console.info('----getWantAgent failed!----');
}
}
// Obtain the WantAgent object.
wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
```
- Publish the notification.
```js
// Create a NotificationRequest object.
var notificationRequest = {
content: {
contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: "AceApplication_Title",
text: "AceApplication_Text",
additionalText: "AceApplication_AdditionalText"
},
},
id: 1,
label: 'TEST',
wantAgent: WantAgent,
slotType: Notification.SlotType.OTHER_TYPES,
deliveryTime: new Date().getTime()
}
// Publish the notification.
Notification.publish(notificationRequest).then((data) => {
console.info('===>publish promise success req.id : ' + notificationRequest.id);
}).catch((err) => {
console.error('===>publish promise failed because ' + JSON.stringify(err));
});
```
- Cancel the notification.
An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself.
```js
// cancel callback
function cancelCallback(err) {
console.info("===>cancelCallback===>");
}
Notification.cancel(1, "label", cancelCallback)
```
# Notification Overview
## Introduction
All system applications and services can publish notifications through the notification APIs. Users can view the notifications in the notification panel or click a notification to open the publishing application.
Below are some typical use cases for notifications:
- Display received SMS messages and instant messages.
- Display push messages, such as advertisements and version updates.
- Display ongoing events, such as the download progress.
The Advanced Notification Service (ANS) in OpenHarmony is used to manage notifications of various types, such as basic notifications, progress notifications, and reminders published through the background agent.
## Notification Service Process
The notification service process involves the notification subsystem, notification sender, and notification subscriber.
A notification is generated by the notification sender and sent to the notification subsystem through [inter-process communication (IPC)](../connectivity/ipc-rpc-overview.md). The notification subsystem then distributes the notification to the notification subscriber.
System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the notification subsystem for storage in the memory and database.
![en-us_image_0000001466582017](figures/en-us_image_0000001466582017.png)
# Notification Subscription (Open Only to System Applications)
To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application.
You can use the **NotificationSubscriber** object to provide callbacks for subscription events, such as subscription success, notification reception, notification cancellation, and subscription cancellation.
## Available APIs
The major APIs for notification subscription are described as follows. For details about the APIs, see [@ohos.notificationSubscribe](../reference/apis/js-apis-notificationSubscribe.md).
**Table 1** Major APIs for notification subscription
| Name | Description|
| -------- | -------- |
| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback&lt;void&gt;): void | Subscribes to notifications from a specific application.|
| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback&lt;void&gt;): void | Subscribes to notifications from all applications. |
**Table 2** Callbacks for notification subscription
| Name | Description|
| -------- | -------- |
| onConsume?:(data: SubscribeCallbackData) =&gt; void | Callback for receiving notifications. |
| onCancel?:(data: SubscribeCallbackData) =&gt; void | Callback for canceling notifications. |
| onUpdate?:(data: NotificationSortingMap) =&gt; void | Callback for notification sorting updates. |
| onConnect?:() =&gt; void; | Callback for subscription. |
| onDisconnect?:() =&gt; void; | Callback for unsubscription. |
| onDestroy?:() =&gt; void | Callback for disconnecting from the notification subsystem. |
| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) =&gt; void | Callback for the Do Not Disturb (DNT) time changes.|
| onEnabledNotificationChanged?:(callbackData: EnabledNotificationCallbackData) =&gt; void | Callback for notification switch changes. |
## How to Develop
1. Request the **ohos.permission.NOTIFICATION_CONTROLLER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Import the **notificationSubscribe** module.
```ts
import notificationSubscribe from '@ohos.notificationSubscribe';
```
3. Create a **subscriber** object.
```ts
let subscriber = {
onConsume: function (data) {
let req = data.request;
console.info('[ANS] onConsume callback req.id: ' + req.id);
},
onCancel: function (data) {
let req = data.request;
console.info('[ANS] onCancel callback req.id: : ' + req.id);
},
onUpdate: function (data) {
console.info('[ANS] onUpdate in test');
},
onConnect: function () {
console.info('[ANS] onConnect in test');
},
onDisconnect: function () {
console.info('[ANS] onDisConnect in test');
},
onDestroy: function () {
console.info('[ANS] onDestroy in test');
},
};
```
4. Initiate notification subscription.
```ts
notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result.
if (err) {
console.error(`[ANS] failed to subscribe, error[${err}]`);
return;
}
console.info(`[ANS] subscribeTest success : + ${data}`);
});
```
# Adding a WantAgent Object to a Notification
A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsulates an intention to start a specified ability, release a common event, and more. In OpenHarmony, a **WantAgent** object can be passed in a notification from the publisher to the subscriber, so as to trigger the intention specified. For example, you may want the user to start a specific ability by touching the notification published by your application. In this case, you can add a **WantAgent** object that encapsulates such an action to the notification. After receiving the **WantAgent** object, the system triggers it once the user touches the notification from the notification panel, starting the specified ability.
Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered.
**Figure 1** Publishing a notification with a WantAgent object
![notification-with-wantagent](figures/notification-with-wantagent.png)
## Available APIs
For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md).
| Name| Description|
| -------- | -------- |
| getWantAgent(info: WantAgentInfo, callback: AsyncCallback&lt;WantAgent&gt;): void | Creates a **WantAgent** object.|
| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback&lt;CompleteData&gt;): void | Triggers a **WantAgent** object.|
| cancel(agent: WantAgent, callback: AsyncCallback&lt;void&gt;): void | Cancels a **WantAgent** object.|
| getWant(agent: WantAgent, callback: AsyncCallback&lt;Want&gt;): void | Obtains a **WantAgent** object.|
| equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether two **WantAgent** objects are equal. |
## How to Develop
1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user.
2. Import the modules.
```typescript
import notificationManager from '@ohos.notificationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
```
3. Create a **WantAgentInfo** object.
Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component.
```typescript
let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations.
// Set the action type through operationType of WantAgentInfo.
let wantAgentInfo = {
wants: [
{
deviceId: '',
bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility',
action: '',
entities: [],
uri: '',
parameters: {}
}
],
operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
};
```
Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md).
```typescript
let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations.
// Set the action type through operationType of WantAgentInfo.
let wantAgentInfo = {
wants: [
{
action: 'event_name', // Set the action name.
parameters: {},
}
],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
}
```
4. Invoke the [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) API to create a **WantAgent** object.
```typescript
// Create a WantAgent object.
wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
if (err) {
console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
return;
}
console.info('[WantAgent]getWantAgent success');
wantAgentObj = data;
});
```
5. Create a **NotificationRequest** object and publish a notification that carries the **WantAgent** object.
```typescript
// Create a NotificationRequest object.
let notificationRequest = {
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'Test_Title',
text: 'Test_Text',
additionalText: 'Test_AdditionalText',
},
},
id: 1,
label: 'TEST',
wantAgent: wantAgentObj,
}
notificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
```
6. When the user touches the notification from the notification panel, the system automatically triggers the action specified in the **WantAgent** object.
# Publishing a Progress Notification
The progress notification is a commonly used notification type, mainly used to display the progress of an ongoing operation, such as file downloading. When publishing a progress notification through the notification subsystem, you can use the readily available template by specifying the related attributes, such as the template name and template data.
In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data.
## Available APIs
| Name| Description|
| -------- | -------- |
| isSupportTemplate(templateName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result.<br>Only the progress-type template is supported.|
## How to Develop
1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user.
2. Import the module.
```ts
import notificationManager from '@ohos.notificationManager';
```
3. Check whether a specific template is supported. In this example, the template of the **downloadTemplate** type is checked.
```ts
notificationManager.isSupportTemplate('downloadTemplate').then((data) => {
console.info(`[ANS] isSupportTemplate success`);
let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite.
// ...
}).catch((err) => {
console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
});
```
> **NOTE**
>
> Proceed with the step below only when the specified template is supported.
4. Create a **NotificationRequest** object and publish a progress notification.
```ts
let notificationRequest = {
id: 1,
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText'
}
},
// Create a progress template. The name field has a fixed value of downloadTemplate.
template: {
name: 'downloadTemplate',
data: { title: 'File Title', fileName: 'music.mp4', progressValue: 45 }
}
}
// Publish the notification.
notificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success `);
});
```
# Publishing a Basic Notification
You can publish basic notifications to send SMS messages, prompt messages, and advertisements. Available content types of basic notifications include normal text, long text, multi-line text, and picture-attached.
**Table 1** Basic notification content types
| Type| Description|
| -------- | -------- |
| NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification.|
| NOTIFICATION_CONTENT_LONG_TEXT | Long text notification.|
| NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.|
| NOTIFICATION_CONTENT_PICTURE | Picture-attached notification.|
Notifications are displayed in the notification panel, which is the only system subscriber to notifications. Below you can see two examples of the basic notification.
**Figure 1** Examples of the basic notification
![en-us_image_0000001466462305](figures/en-us_image_0000001466462305.png)
## Available APIs
The following table describes the APIs for notification publishing. You specify the notification type by setting the [NotificationRequest](../reference/apis/js-apis-notificationManager.md#notificationrequest) parameter in the APIs.
| Name| Description|
| -------- | -------- |
| publish(request: NotificationRequest, callback: AsyncCallback&lt;void&gt;): void | Publishes a notification. |
| cancel(id: number, label: string, callback: AsyncCallback&lt;void&gt;): void | Cancels a notification. |
| cancelAll(callback: AsyncCallback&lt;void&gt;): void; | Cancels all notifications published by the application.|
## How to Develop
1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user.
2. Import the module.
```ts
import notificationManager from '@ohos.notificationManager';
```
3. Create a **NotificationRequest** object and publish a progress notification.
- A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes.
```ts
let notificationRequest = {
id: 1,
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification
normal: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
}
}
}
notificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
```
Below is an example of the normal text notification.
![en-us_image_0000001466782033](figures/en-us_image_0000001466782033.png)
- In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively.
```ts
let notificationRequest = {
id: 1,
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification
longText: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
longText: 'test_longText',
briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle',
}
}
}
// Publish the notification.
notificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
```
Below is an example of the long-text notification.
![en-us_image_0000001416745530](figures/en-us_image_0000001416745530.png)
- In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively.
```ts
let notificationRequest = {
id: 1,
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification
multiLine: {
title: 'test_title',
text: 'test_text',
briefText: 'test_briefText',
longTitle: 'test_longTitle',
lines: ['line_01', 'line_02', 'line_03', 'line_04'],
}
}
}
// Publish the notification.
notificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success`);
});
```
Below is an example of the multi-line notification.
![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png)
- In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB.
```ts
let notificationPicture: PixelMap = undefined; // Obtain the pixel map information.
let notificationRequest = {
id: 1,
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
picture: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText',
briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle',
picture: notificationPicture
}
}
}
// Publish the notification.
notificationManager.publish(notificationRequest, (err) => {
if (err) {
console.error(`[ANS] failed to publish, error[${err}]`);
return;
}
console.info(`[ANS] publish success `);
});
```
Below is an example of the picture-attached notification.
![en-us_image_0000001466582045](figures/en-us_image_0000001466582045.png)
......@@ -194,23 +194,24 @@
- [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md)
- Security
- [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager](js-apis-privacyManager.md)
- [@ohos.security.cryptoFramework](js-apis-cryptoFramework.md)
- [@ohos.security.huks ](js-apis-huks.md)
- [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
- [@system.cipher](js-apis-system-cipher.md)
- [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md)
- [@ohos.security.cert (Certificate)](js-apis-cert.md)
- [@ohos.security.cryptoFramework (Crypto Framework)](js-apis-cryptoFramework.md)
- [@ohos.security.huks (HUKS)](js-apis-huks.md)
- [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md)
- [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md)
- Data Management
- [@ohos.data.dataAbility ](js-apis-data-ability.md)
- [@ohos.data.dataShare](js-apis-data-dataShare.md)
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md)
- [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md)
- [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md)
- [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md)
- [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet (DataShare Result Set)](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedDataObject (Distributed Data Object)](js-apis-data-distributedobject.md)
- [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md)
- [@ohos.data.preferences (Preferences)](js-apis-data-preferences.md)
- [@ohos.data.rdb (RDB)](js-apis-data-rdb.md)
- [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md)
- data/rdb
- [resultSet](js-apis-data-resultset.md)
- File Management
......@@ -307,6 +308,7 @@
- [@ohos.sensor](js-apis-sensor.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.stationary](js-apis-stationary.md)
- [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md)
- [@ohos.systemParameterV9](js-apis-system-parameterV9.md)
- [@ohos.thermal](js-apis-thermal.md)
- [@ohos.update](js-apis-update.md)
......@@ -324,7 +326,7 @@
- [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md)
- Language Base Class Library
- [@ohos.buffer](js-apis-buffer.md)
- [@ohos.buffer (Buffer)](js-apis-buffer.md)
- [@ohos.convertxml](js-apis-convertxml.md)
- [@ohos.process](js-apis-process.md)
- [@ohos.uri](js-apis-uri.md)
......
# Ability Access Control
# @ohos.abilityAccessCtrl (Ability Access Control)
The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation.
......
# @ohos.app.ability.appRecovery
# @ohos.app.ability.appRecovery (Application Recovery)
The **appRecovery** module provides APIs for recovering faulty applications.
The **appRecovery** module provides APIs for recovering failed applications.
> **NOTE**
>
......
# @ohos.app.ability.errorManager
# @ohos.app.ability.errorManager (Error Manager)
The **ErrorManager** module provides APIs for registering and deregistering error observers.
The **errorManager** module provides APIs for registering and deregistering error observers.
> **NOTE**
>
......
# @ohos.application.errorManager
# @ohos.application.errorManager (Error Manager)
The **ErrorManager** module provides APIs for registering and deregistering error observers.
The **errorManager** module provides APIs for registering and deregistering error observers.
> **NOTE**
>
......
# @ohos.batteryInfo
# @ohos.batteryInfo (Battery Information)
The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status.
> **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
```js
......
# @ohos.batteryStatistics
# @ohos.batteryStatistics (Battery Statistics)
The **batteryStatistics** module provides APIs for querying software and hardware power consumption statistics.
......
# Performance Tracing
# @ohos.bytrace (Performance Tracing)
> **NOTE**
> - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead.
......
# Call
# @ohos.telephony.call (Call)
The call module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers.
The **call** module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers.
To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-observer.md#observeroncallstatechange).
......
此差异已折叠。
# Contacts
# @ohos.contact (Contacts)
>**NOTE**
>
......
# @ohos.data.dataShareResultSet
# @ohos.data.dataShareResultSet (DataShare Result Set)
The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type.
......
# @ohos.data.dataShare
# @ohos.data.dataShare (DataShare)
The **DataShare** module allows an application to manage its own data and share data with other applications on the same device.
......
# Data Share Predicates
# @ohos.data.dataSharePredicates (DataShare Predicates)
You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data.
......@@ -35,7 +35,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
......@@ -65,7 +65,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
......@@ -439,8 +439,8 @@ Currently, only the RDB supports this **DataSharePredicates** object.
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ------------------------ |
| field | string | Yes | Column name in the database table. |
| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.|
| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.|
| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.|
| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.|
**Return value**
......@@ -470,8 +470,8 @@ Currently, only the RDB supports this **DataSharePredicates** object.
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ------------------------ |
| field | string | Yes | Column name in the database table. |
| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.|
| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.|
| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.|
| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.|
**Return value**
......@@ -501,7 +501,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | --------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
......@@ -531,7 +531,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
......@@ -561,7 +561,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | --------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
......@@ -591,7 +591,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | --------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
......@@ -790,7 +790,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | --------------------------------------- |
| field | string | Yes| Column name in the database table. |
| value | Array&lt;[ValueType](js-apis-data-ValuesBucket.md#valuetype)&gt; | Yes | Array of the values to match.|
| value | Array&lt;[ValueType](js-apis-data-valuesBucket.md#valuetype)&gt; | Yes | Array of the values to match.|
**Return value**
......@@ -820,7 +820,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | --------------------------------------- |
| field | string | Yes | Column name in the database table. |
| value | Array&lt;[ValueType](js-apis-data-ValuesBucket.md#valuetype)&gt; | Yes | Array of the values to match.|
| value | Array&lt;[ValueType](js-apis-data-valuesBucket.md#valuetype)&gt; | Yes | Array of the values to match.|
**Return value**
......
# Distributed Data Object
# @ohos.data.distributedDataObject (Distributed Data Object)
The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices.
......@@ -23,9 +23,9 @@ Creates a distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.|
**Return value**
| Type| Description|
......@@ -49,9 +49,9 @@ Creates a random session ID.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value**
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
**Example**
```js
......@@ -97,15 +97,15 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example**
......@@ -128,10 +128,10 @@ Subscribes to the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
......@@ -157,10 +157,10 @@ Unsubscribes from the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
......@@ -182,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example**
```js
......@@ -207,10 +207,10 @@ Unsubscribes from the status change (online or offline) of this distributed data
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.|
**Example**
......@@ -243,10 +243,10 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```js
......@@ -279,15 +279,15 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
......@@ -317,9 +317,9 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
......@@ -345,9 +345,9 @@ If the object is stored on another device, the data on the local device will be
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
......
# Preferences
# @ohos.data.preferences (Preferences)
The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required.
......@@ -497,7 +497,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data to obtain. It cannot be empty. |
......
# @ohos.data.rdb
# @ohos.data.rdb (RDB)
The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements.
......
......@@ -62,8 +62,8 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
console.info("Failed to get RdbStore, err: " + err)
return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
console.log("RdbStore status is ON_CREATA")
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
......@@ -97,8 +97,8 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
console.info("Failed to get RdbStore, err: " + err)
return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
console.log("RdbStore status is ON_CREATA")
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
......@@ -154,8 +154,8 @@ const STORE_CONFIG = {
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
console.log("RdbStore status is ON_CREATA")
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
......@@ -188,8 +188,8 @@ const STORE_CONFIG = {
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
console.log("RdbStore status is ON_CREATA")
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
......
# @ohos.data.ValuesBucket
# @ohos.data.ValuesBucket (Value Bucket)
The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database.
......@@ -34,6 +34,6 @@ Defines the types of the key and value in a KV pair.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Key Type | Value Type |
| ------------- | --------------------------------------------- |
| string | [ValueType](#valuetype)\| Uint8Array \| null |
| Key Type | Value Type |
| ------------- | --------------------------------------------- |
| string | [ValueType](#valuetype)\| Uint8Array \| null |
# Distributed KV Store
# @ohos.data.distributedKVStore (Distributed KV Store)
The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores.
......@@ -2395,7 +2395,7 @@ Writes data to this single KV store. This API uses an asynchronous callback to r
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
| value | Array&lt;[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)&gt; | Yes | Data to write.|
| value | Array&lt;[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)&gt; | Yes | Data to write.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes**
......@@ -2447,7 +2447,7 @@ Write data to this KV store. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------ |
| value | Array&lt;[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)&gt; | Yes | Data to write. |
| value | Array&lt;[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)&gt; | Yes | Data to write. |
**Return value**
......
# @ohos.faultLogger
# @ohos.faultLogger (Fault Logger)
The **faultLogger** module implements fault logging functions.
......
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册