提交 c3aa3d46 编写于 作者: zyjhandsome's avatar zyjhandsome

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

......@@ -56,20 +56,20 @@ Users often need to share data (such as a text or an image) from one application
}
}
}
```
In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved:
```
In the preceding code, the custom field **parameters** is used. The **ability.picker.\*** fields in the first-layer **parameters** are used to pass the information to be displayed on the application selector. The following fields are involved:
- **"ability.picker.type"**: The application selector renders the file type icon based on this field.
- **"ability.picker.fileNames"**: The application selector displays the file name based on this field.
- **"ability.picker.fileSizes"**: The application selector displays the file size based on this field. The unit is byte.
- **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping.
- **"ability.picker.fileNames"** and **"ability.picker.fileSizes"** are arrays and have a one-to-one mapping.
For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows:
<img src="figures/stage-want2.png" alt="stage-want2" style="zoom:50%;" />
In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Implicit Want Matching Rules](explicit-implicit-want-mappings.md#interpretation-of-implicit-want-matching-rules). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application.
In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application.
- Shared party
1. As mentioned above, the application selector performs implicit matching based on the **ability.want.params.INTENT** field. Therefore, you must set **skills** in the ability configuration file (**module.json5** file in the stage model) of the shared party as follows:
......
......@@ -33,4 +33,4 @@ To enable an ability to be called by any application, configure the **config.jso
```
If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#interpretation-of-implicit-want-matching-rules) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant.
If the ability contains **skills**, you are advised to set **visible** to **true** so that the ability can be [implicitly started](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want) by other applications. If this attribute is set to **false**, the system returns **PERMISSION_DENIED** when other applications attempt to start the ability. In this case, a system application can request the [START_INVISIBLE_ABILITY](../security/permission-list.md) permission to start the ability. Example abilities with **visible** set to **false** are home screen, voice assistant, or search assistant.
# Geocoding and Reverse Geocoding Capabilities
## When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa.
The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address.
## Available APIs
The following table describes APIs available for mutual conversion between coordinates and geographic description. For details, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
**Table1** APIs for geocoding and reverse geocoding
| API | Description |
| -------- | -------- |
| isGeocoderAvailable(): boolean; | Checks whether the (reverse) geocoding service is available.|
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;): void | Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest): Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. |
## How to Develop
> **NOTE**
>
> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
1. Import the **geoLocationManager** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
```ts
import geoLocationManager from '@ohos.geolocation';
```
2. Query whether geocoder service is available.
- Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
var isAvailable = geoLocationManager.isGeocoderAvailable();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
3. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information.
```ts
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
- Call **getAddressesFromLocationName** to convert geographic description into coordinates.
```ts
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
try {
geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
});
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
# Obtaining Device Location Information
## When to Use
You can call location-related APIs in OpenHarmony to obtain the real-time location or last known location of a mobile device.
Real-time location of the device is recommended for location-sensitive services. If you want to lower power consumption when the real-time location of the device is not needed, you may consider obtaining the last known location of the device.
## Available APIs
For details about the APIs used to obtain the device location information, see [Geolocation Manager](../reference/apis/js-apis-geoLocationManager.md).
## How to Develop
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geoLocationManager.md).
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below.
The system provides the following location permissions:
- ohos.permission.LOCATION
- ohos.permission.APPROXIMATELY_LOCATION
- ohos.permission.LOCATION_IN_BACKGROUND
If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking:
API versions earlier than 9: Apply for **ohos.permission.LOCATION**.
API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately.
| Target API Level| Location Permission| Permission Application Result| Location Accuracy|
| -------- | -------- | -------- | -------- |
| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters|
| 9 and later| ohos.permission.LOCATION | Failure| No location obtained|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers|
| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters|
If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
2. Import the **geoLocationManager** module by which you can implement all APIs related to the basic location capabilities.
```ts
import geoLocationManager from '@ohos.geolocation';
```
3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.<br>
**Method 1:**
To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported.
```
export enum LocationRequestScenario {
UNSET = 0x300,
NAVIGATION,
TRAJECTORY_TRACKING,
CAR_HAILING,
DAILY_LIFE_SERVICE,
NO_POWER,
}
```
**Table 2** Common use cases of the location function
| Use Case | Constant | Description |
| ------------ | ------------------- | ------------------------------------------------------------ |
| Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
Sample code for initializing **requestInfo** for navigation:
```ts
var requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
**Method 2:**
If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system.
```ts
export enum LocationRequestPriority {
UNSET = 0x200,
ACCURACY,
LOW_POWER,
FIRST_FIX,
}
```
**Table 3** Location priority policies
| Policy | Constant | Description |
| ------------------ | -------------- | ------------------------------------------------------------ |
| Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.|
| Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.<br>To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.|
Sample code for initializing **requestInfo** for the location accuracy priority policy:
```ts
var requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
```
4. Instantiate the **Callback** object for the system to report location results.
Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic.
```ts
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
```
5. Start device location.
```ts
geoLocationManager.on('locationChange', requestInfo, locationChange);
```
6. (Optional) Stop device location.
```ts
geoLocationManager.off('locationChange', locationChange);
```
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```ts
import geoLocationManager from '@ohos.geoLocationManager';
try {
var location = geoLocationManager.getLastLocation();
} catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message);
}
```
To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user.
# Location Overview
People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices.
With the location awareness capability offered by , mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users.
Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording.
## Basic Concepts
Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System (GNSS) and network positioning (for example, base station positioning or WLAN/Bluetooth positioning) to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors.
- **Coordinate**
A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
- **GNSS positioning**
GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device.
- **Base station positioning**
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network.
- **WLAN or Bluetooth positioning**
WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network.
## Working Principles
Location awareness is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a location request to the system and stop the location request when the service scenario ends. In this process, the system reports the location information to the application on a real-time basis.
## Limitations and Constraints
Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application.
Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information.
## Samples
The following sample is provided to help you better understand how to develop location services:
-[`Location`: Location (eTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location)
......@@ -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.
......
# Internationalization
- [Internationalization Overview](international-overview.md)
- [Internationalization Development (intl)](intl-guidelines.md)
- [Internationalization Development (i18n)](i18n-guidelines.md)
- [intl Development](intl-guidelines.md)
- [i18n Development](i18n-guidelines.md)
# 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)
......
# @ohos.enterprise.EnterpriseAdminExtensionAbility
# @ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)
The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators.
......
# Work Scheduler Callbacks
# @ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)
The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks.
......
# @ohos.ability.ability
# @ohos.ability.ability (Ability)
The **Ability** module provides all level-2 module APIs for developers to export.
......
# @ohos.ability.dataUriUtils
# @ohos.ability.dataUriUtils (dataUriUtils)
The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module.
......
# @ohos.ability.errorCode
# @ohos.ability.errorCode (ErrorCode)
The **ErrorCode** module defines the error codes that can be used when the ability is started.
**NOTE**
The **ErrorCode** module defines the error codes that may be returned when an ability is started.
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -14,13 +14,13 @@ import errorCode from '@ohos.ability.errorCode'
## ErrorCode
Defines the error codes used when the ability is started.
Enumerates the error codes that may be returned when an ability is started.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ------------------------------ | ---- | ---------------------------------------- |
| NO_ERROR | 0 | No error occurs. |
| NO_ERROR | 0 | No error. |
| INVALID_PARAMETER | -1 | Invalid parameter.|
| ABILITY_NOT_FOUND | -2 | The ability is not found.|
| PERMISSION_DENY | -3 | Permission denied. |
# @ohos.ability.wantConstant
# @ohos.ability.wantConstant (wantConstant)
The **wantConstant** module provides the actions, entities, and flags used in **Want** objects.
......@@ -14,7 +14,7 @@ import wantConstant from '@ohos.ability.wantConstant';
## wantConstant.Action
Enumerates the action constants of the **Want** object.
Enumerates the action constants of the **Want** object. **action** specifies the operation to execute.
**System capability**: SystemCapability.Ability.AbilityBase
......@@ -57,7 +57,7 @@ Enumerates the action constants of the **Want** object.
## wantConstant.Entity
Enumerates the entity constants of the **Want** object.
Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability.
**System capability**: SystemCapability.Ability.AbilityBase
......@@ -72,25 +72,25 @@ Enumerates the entity constants of the **Want** object.
## wantConstant.Flags
Describes flags.
Enumerates the flags that specify how the Want will be handled.
**System capability**: SystemCapability.Ability.AbilityBase
| 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 data to the URI. |
| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. |
| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to the URI. |
| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. |
| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. |
| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. |
| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. |
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. |
| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.<br>**System API**: This is a system API and cannot be called by third-party applications.|
| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. |
| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ServiceAbility is started regardless of whether the host application has been started. |
| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. |
| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. |
| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.|
| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. |
| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.|
| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the history mission stack. |
| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.|
# @ohos.app.ability.Ability
# @ohos.app.ability.Ability (Ability Base Class)
The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information.
This is the base class of [UIAbility](js-apis-app-ability-uiAbility.md) and [ExtensionAbility](js-apis-app-ability-extensionAbility.md). It provides the callbacks for system configuration updates and memory level updates. You cannot inherit from this base class.
> **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.
## Modules to Import
```ts
import Ability from '@ohos.app.ability.Ability';
```
## Ability.onConfigurationUpdate
onConfigurationUpdate(newConfig: Configuration): void;
......@@ -23,40 +17,45 @@ Called when the configuration of the environment where the ability is running is
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.|
**Example**
```ts
class myAbility extends Ability {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config));
}
}
// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example.
import UIAbility from '@ohos.app.ability.UIAbility';
class MyUIAbility extends UIAbility {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config));
}
}
```
## Ability.onMemoryLevel
onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible.
Called when the system adjusts the memory level.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.|
**Example**
```ts
class myAbility extends Ability {
// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example.
import UIAbility from '@ohos.app.ability.UIAbility';
class MyUIAbility extends UIAbility {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
}
```
# @ohos.app.ability.dataUriUtils
# @ohos.app.ability.dataUriUtils (DataUriUtils)
The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI.
......
# @ohos.app.ability.wantAgent
# @ohos.app.ability.wantAgent (WantAgent)
The **app.ability.WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future.
......
# @ohos.application.context
# @ohos.application.context (Context)
The **Context** module provides all level-2 module APIs for developers to export.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册