With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group.
The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported.
## Available APIs
Import the **stats** package to implement registration:
```js
importstatsfrom'@ohos.bundleState';
```
**Table 1** Major APIs for device usage statistics
| API| Description|
| -------- | -------- |
| function queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void | Queries events of all applications based on the specified start time and end time.|
| function queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void | Queries the application usage duration statistics based on the specified start time and end time.|
| function queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveState>>): void | Queries events of this application based on the specified start time and end time.|
| function queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStateInfo>>): void | Queries the application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually).|
| function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function getRecentlyUsedModules(callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains a maximum of 1000 FA usage records. |
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**, which cannot exceed 1000.|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function queryAppUsagePriorityGroup(bundleName : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(bundleName? : string): Promise<number>; | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses a promise to return the result.|
| function setBundleGroup(bundleName : string, newGroup: GroupType, callback: AsyncCallback>boolean>): void | Sets the group for the application specified by **bundleName**. This API uses an asynchronous callback to return the result.|
| function setBundleGroup(bundleName : string, newGroup : GroupType): Promise>boolean>; | Sets the group for the application specified by **bundleName**. This API uses a promise to return the result.|
| function registerGroupCallBack(groupCallback: Callback>BundleActiveGroupCallbackInfo>, callback: AsyncCallback>boolean>): void | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.|
| function registerGroupCallBack(groupCallback: Callback>BundleActiveGroupCallbackInfo>): Promise>boolean>; | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses a promise to return the result.|
| function unRegisterGroupCallBack(callback: AsyncCallback>boolean>): void | Deregisters the callback for application group changes. This API uses an asynchronous callback to return the result.|
| function unRegisterGroupCallBack(): Promise>boolean>; | Deregisters the callback for application group changes. This API uses a promise to return the result.|
## How to Develop
1. Configure the device usage statistics permission in the **config.json** file.
```json
"module": {
"package": "com.example.deviceUsageStatistics",
...,
"reqPermissions": [
{
"name": "ohos.permission.BUNDLE_ACTIVE_INFO"
}
]
}
```
2. Query events of all applications based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file.
console.log('BUNDLE_ACTIVE queryBundleActiveStates callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates callback result ' + JSON.stringify(res[i]));
}
}
});
```
3. Query the application usage duration statistics based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file.
console.log('BUNDLE_ACTIVE queryBundleStateInfos callback number : ' + i);
console.log('BUNDLE_ACTIVE queryBundleStateInfos callback result ' + JSON.stringify(res[key]));
i++;
}
}
});
```
4. Query events of this application based on the specified start time and end time. This requires no permission to be configured in the **config.json** file.
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback result ' + JSON.stringify(res[i]));
}
}
});
```
5. Query the application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually). This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file.
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself.
8. Obtain the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file.
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback result ' + JSON.stringify(res[i]));
}
}
});
```
9. Query the number of notifications from all applications based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file.
console.log('BUNDLE_ACTIVE queryAppNotificationNumber callback result ' + JSON.stringify(res));
}
});
```
10. Query statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file.
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates callback result ' + JSON.stringify(res));
}
});
```
11. Query the priority group of the current application. This requires no permission to be configured in the **config.json** file. Query the priority group of a specified application. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured in the **config.json** file.
12. Register a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback.
# Device Usage Statistics Development (API Version 9)
## When to Use
With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and application group.
The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported.
## Available APIs
Import the **stats** package to implement registration:
**Table 1** Major APIs for device usage statistics
| API| Description|
| -------- | -------- |
| function queryBundleEvents(begin: number, end: number, callback: AsyncCallback<Array<BundleEvents>>): void | Queries events of all applications based on the specified start time and end time.|
| function queryBundleStatsInfos(begin: number, end: number, callback: AsyncCallback<BundleStatsMap>): void | Queries the application usage duration statistics based on the specified start time and end time.|
| function queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback<Array<BundleEvents>>): void | Queries events of this application based on the specified start time and end time.|
| function queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback<Array<BundleStatsInfo>>): void | Queries the application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually).|
| function queryAppGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.|
| function queryAppGroup(bundleName : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. This API uses an asynchronous callback to return the result.|
| function queryAppGroup(bundleName : string): Promise<number>; | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function queryModuleUsageRecords(callback: AsyncCallback<HapModuleInfo>): void | Obtains a maximum of 1000 FA usage records.|
| function queryModuleUsageRecords(maxNum: number, callback: AsyncCallback<HapModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**, which cannot exceed 1000.|
| function queryNotificationEventStats(begin: number, end: number, callback: AsyncCallback<Array<DeviceEventStats>>): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback<Array<DeviceEventStats>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function setAppGroup(bundleName : string, newGroup: GroupType, callback: AsyncCallback>boolean>): void | Sets the group for the application specified by **bundleName**. This API uses an asynchronous callback to return the result.|
| function setAppGroup(bundleName : string, newGroup : GroupType): Promise>boolean>; | Sets the group for the application specified by **bundleName**. This API uses a promise to return the result.|
| function registerAppGroupCallBack(groupCallback: Callback>AppGroupCallbackInfo>, callback: AsyncCallback>boolean>): void | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.|
| function registerAppGroupCallBack(groupCallback: Callback>AppGroupCallbackInfo>): Promise>boolean>; | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses a promise to return the result.|
| function unregisterAppGroupCallBack(callback: AsyncCallback>boolean>): void | Deregisters the callback for application group changes. This API uses an asynchronous callback to return the result.|
| function unregisterAppGroupCallBack(): Promise>boolean>; | Deregisters the callback for application group changes. This API uses a promise to return the result.|
## How to Develop
1. Before obtaining the device usage statistics, check whether the **ohos.permission.BUNDLE_ACTIVE_INFO** permission is configured. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Query events of all applications based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
try{
usageStatistics.queryBundleEvents(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryBundleEvents callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleEvents callback result ' + JSON.stringify(res[i]));
}
}
});
} catch (error) {
console.log('BUNDLE_ACTIVE queryBundleEvents throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
3. Query the application usage duration statistics based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
try{
usageStatistics.queryBundleStatsInfos(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback result ' + JSON.stringify(res[i]));
}
}
});
} catch (error) {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
5. Query the application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually). This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
try{
usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured. A third-party application can only check the idle status of itself.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
try{
usageStatistics.isIdleState("com.ohos.camera").then( res => {
console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
8. Obtain the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
try{
usageStatistics.queryModuleUsageRecords(1000).then( res => {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback result ' + JSON.stringify(res[i]));
}
}
});
} catch (error) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
9. Query the number of notifications from all applications based on the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
try{
usageStatistics.queryNotificationEventStats(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryNotificationEventStats callback result ' + JSON.stringify(res));
}
});
} catch (error) {
console.log('BUNDLE_ACTIVE queryNotificationEventStats throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
10. Query statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
try{
usageStatistics.queryDeviceEventStats(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryDeviceEventStats callback result ' + JSON.stringify(res));
}
});
} catch (error) {
console.log('BUNDLE_ACTIVE queryDeviceEventStats throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
11. Query the priority group of the application specified by **bundleName**. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode when bundleName is specified
let bundleName = "com.ohos.camera";
try{
usageStatistics.queryAppGroup(bundleName).then( res => {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
12. Set the priority group of for application specified by **bundleName**. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```javascript
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// Promise mode
let bundleName = "com.example.deviceUsageStatistics";
let newGroup = bundleState.GroupType.ACTIVE_GROUP_DAILY;
console.log('BUNDLE_ACTIVE setAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
}
```
13. Register a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This requires the **ohos.permission.BUNDLE_ACTIVE_INFO** permission to be configured.
```javascript
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
@@ -8,11 +8,11 @@ If an application has a task that needs to be continued when the application is
...
@@ -8,11 +8,11 @@ If an application has a task that needs to be continued when the application is
If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task.
If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task.
If a privileged system application needs to use certain system resources (for example, resources required to receive common events) when suspended, it can request efficiency resources.
If a privileged system application needs to use certain system resources (for example, it wants to receive common events when suspended), it can request efficiency resources.
> **NOTE**
> **NOTE**
>
> - This module is deprecated since API version 9. You are advised to use [@ohos.resourceschedule.backgroundTaskManager](js-apis-resourceschedule-backgroundTaskManager.md) instead.
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Requests delayed suspension after the application switches to the background.
Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.
The default duration of delayed suspension is 3 minutes when the battery level is higher than or equal to the broadcast low battery level and 1 minute when the battery level is lower than the broadcast low battery level.
| reason | string | Yes | Reason for delayed transition to the suspended state. |
| reason | string | Yes | Reason for delayed transition to the suspended state. |
| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.|
| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.|
| requestId | number | Yes | ID of the suspension delay request. |
| requestId | number | Yes | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).|
| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.|
| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.|
| requestId | number | Yes | ID of the suspension delay request.|
| requestId | number | Yes | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).|
| requestId | number | Yes | ID of the suspension delay request.|
| requestId | number | Yes | ID of the suspension delay request. The value is obtained by calling [requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay).|
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
...
@@ -154,6 +167,9 @@ Requests a continuous task from the system. This API uses an asynchronous callba
...
@@ -154,6 +167,9 @@ Requests a continuous task from the system. This API uses an asynchronous callba
| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
@@ -205,11 +258,15 @@ Requests a continuous task from the system. This API uses a promise to return th
...
@@ -205,11 +258,15 @@ Requests a continuous task from the system. This API uses a promise to return th
| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. |
| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. |
**Return value**
**Return value**
| Type | Description |
| Type | Description |
| -------------- | ---------------- |
| -------------- | ---------------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise used to return the result.|
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
**Return value**
**Return value**
| Type | Description |
| Type | Description |
| -------------- | ---------------- |
| -------------- | ---------------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise used to return the result.|
A process and its application can request the same type of resources at the same time, for example, CPU resources. When the application releases the resources, the same type of resources requested by the process are also released.
| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest9) | Yes | Necessary information carried in the request, including the resource type and timeout interval. For details, see [EfficiencyResourcesRequest](#efficiencyresourcesrequest9).|
**Return value**
| Type | Description |
| -------------- | ---------------- |
| boolean | Returns **true** if the request for the resources is successful; returns **false** otherwise.|
| resourceTypes | number | Yes | Type of the resource to request. |
| isApply | boolean | Yes | Whether the request is used to apply for resources. The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources. |
| timeOut | number | Yes | Duration for which the resource will be used, in milliseconds. |
| isPersist | boolean | No | Whether the resource is permanently held. If the value is **true**, **timeOut** is invalid. |
| isProcess | boolean | No | Whether the request is initiated by a process. The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. |
| reason | string | Yes | Reason for requesting the resource. |
@@ -5,11 +5,8 @@ This module provides APIs for collecting statistics on device usage.
...
@@ -5,11 +5,8 @@ This module provides APIs for collecting statistics on device usage.
System applications can call these APIs to implement the following features:
System applications can call these APIs to implement the following features:
- Query the usage duration in different time segments, events (foreground, background, start and end of continuous tasks), and the number of notifications, on a per application basis.
- Query the usage duration in different time segments, events (foreground, background, start and end of continuous tasks), and the number of notifications, on a per application basis.
- Query statistics about system events (sleep, wakeup, unlock, and screen lock).
- Query the bundle group information of the invoking application itself.
- Query the bundle group information of applications, including the invoking application itself.
- Query the idle status of applications, including the invoking application itself.
- Query the idle status of applications, including the invoking application itself.
- Set the bundle group for other applications.
- Register and deregister the callback for application group changes.
Third-party applications can call these APIs to implement the following features:
Third-party applications can call these APIs to implement the following features:
...
@@ -19,12 +16,15 @@ Third-party applications can call these APIs to implement the following features
...
@@ -19,12 +16,15 @@ Third-party applications can call these APIs to implement the following features
> **NOTE**
> **NOTE**
>
>
> This module is deprecated since API version 9. You are advised to use [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md) instead.
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
## Modules to Import
## Modules to Import
```
```js
importbundleStatefrom'@ohos.bundleState'
importbundleStatefrom'@ohos.bundleState'
```
```
...
@@ -32,7 +32,7 @@ import bundleState from '@ohos.bundleState'
...
@@ -32,7 +32,7 @@ import bundleState from '@ohos.bundleState'
Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. A third-party application can only check the idle status of itself.
Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. By default, a third-party application can only check the idle state of itself. To query the idle state of other applications, it must request the **ohos.permission.BUNDLE_ACTIVE_INFO** permission.
| bundleName | string | Yes | Bundle name of an application. |
| bundleName | string | Yes | Bundle name of an application. |
| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns the idle state of the application if the specified **bundleName** is valid; returns **null** otherwise.|
| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the specified **bundleName** is valid, the idle state of the application is returned; otherwise, **null** is returned.|
Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. A third-party application can only check the idle status of itself.
Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. By default, a third-party application can only check the idle state of itself. To query the idle state of other applications, it must request the **ohos.permission.BUNDLE_ACTIVE_INFO** permission.
| Promise<boolean> | Promise used to return the result. Returns the idle state of the application if the specified **bundleName** is valid; returns **null** otherwise.|
| Promise<boolean> | Promise used to return the result. If the specified **bundleName** is valid, the idle state of the application is returned; otherwise, **null** is returned.|
**Example**
**Example**
...
@@ -97,7 +97,7 @@ Queries the priority group of this application. This API uses a promise to retur
...
@@ -97,7 +97,7 @@ Queries the priority group of this application. This API uses a promise to retur
| Type | Description |
| Type | Description |
| --------------- | --------------------------- |
| --------------- | --------------------------- |
| Promise<number> | Promise used to return the result.|
| Promise<number> | Promise used to return the priority group.|
**Example**
**Example**
...
@@ -121,7 +121,7 @@ Queries the priority group of this application. This API uses an asynchronous ca
...
@@ -121,7 +121,7 @@ Queries the priority group of this application. This API uses an asynchronous ca
| maxNum | number | No | Maximum number of returned records. The maximum and default value is **1000**. If this parameter is not specified, **1000** is used.|
Obtains the number of FA usage records specified by **maxNum**. This API uses an asynchronous callback to return the records sorted by time (most recent first).
Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses a promise to return the result.
| bundleName | string | No | Bundle name of the target application. If this parameter is not specified, the priority group of the current application is queried.|
**Return value**
| Type | Description |
| --------------- | --------------------------- |
| Promise<number> | Promise used to return the result.|
Registers a callback for application group changes. When an application group of the user changes, a **[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)** instance is returned to all applications that have registered the callback. This API uses a promise to return the result.
| callback | Callback<[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)> | Yes | Callback used to return the application group changes.|
**Return value**
| Type | Description |
| ------------- | ----------------------- |
| Promise<void> | Promise used to return the result. |
Registers a callback for application group changes. When an application group of the user changes, a **[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)** instance is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.
| callback | Callback<[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)> | Yes | Callback used to return the application group changes. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time. This API uses a promise to return the result.
Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time. This API uses an asynchronous callback to return the result.
Queries the number of notifications from all applications based on the specified start time and end time. This API uses a promise to return the result.
Queries the number of notifications from all applications based on the specified start time and end time. This API uses an asynchronous callback to return the result.
| appUsageOldGroup | number | Yes | Application group before the change.|
| appUsageNewGroup | number | Yes | Application group after the change.|
| userId | number | Yes | User ID. |
| changeReason | number | Yes | Reason for the group change. |
| bundleName | string | Yes | Bundle name of an application. |
## BundleStateInfo
## BundleStateInfo
Provides the usage duration information of applications.
Provides the usage duration information of an application.
### Attributes
### Attributes
...
@@ -1074,18 +446,20 @@ Provides the usage duration information of applications.
...
@@ -1074,18 +446,20 @@ Provides the usage duration information of applications.
| bundleName | string | Yes | Bundle name of an application. |
| bundleName | string | Yes | Bundle name of an application. |
| abilityPrevAccessTime | number | Yes | Last time when the application was used. |
| abilityPrevAccessTime | number | Yes | Last time when the application was used. |
| abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. |
| abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. |
| id | number | No | User ID.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| id | number | No | User ID.|
| abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.|
| abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.|
| fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.|
| fgAbilityPrevAccessTime | number | No | Last time when the application accessed the foreground.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| fgAbilityPrevAccessTime | number | No | Last time when the application accessed the foreground.|
| infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.|
| infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.|
## BundleActiveState
## BundleActiveState
Provides information about an application event.
Provides information about an application event.
Provides the usage duration information of applications.
| stateOccurredTime | number | Yes | Timestamp when the application event occurs. |
| stateOccurredTime | number | Yes | Timestamp when the application event occurs. |
| appUsagePriorityGroup | number | No | Usage priority group of the application.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| appUsagePriorityGroup | number | No | Usage priority group of the application.|
| indexOfLink | string | No | Shortcut ID.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| indexOfLink | string | No | Shortcut ID.|
| nameOfClass | string | No | Class name.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| nameOfClass | string | No | Class name.|
## BundleActiveInfoResponse
## BundleActiveInfoResponse
...
@@ -1107,20 +481,6 @@ Provides the usage duration information of applications.
...
@@ -1107,20 +481,6 @@ Provides the usage duration information of applications.
@@ -203,7 +203,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba
...
@@ -203,7 +203,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba
| Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| id | number | Yes| Notification ID of a continuous task.|
| id | number | Yes| Notification ID of a continuous task.|
| request | NotificationRequest | Yes| Notification parameter, which is used to display information in the notification bar.|
| request | [NotificationRequest](js-apis-notification.md#notificationrequest) | Yes| Notification parameter, which is used to display information in the notification bar.|
| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
**Example**
**Example**
...
@@ -215,7 +215,7 @@ import wantAgent from '@ohos.wantAgent';
...
@@ -215,7 +215,7 @@ import wantAgent from '@ohos.wantAgent';
@@ -267,7 +267,7 @@ Requests a continuous task from the system. This API uses a promise to return th
...
@@ -267,7 +267,7 @@ Requests a continuous task from the system. This API uses a promise to return th
| Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| id | number | Yes| Notification ID of a continuous task.|
| id | number | Yes| Notification ID of a continuous task.|
| request | NotificationRequest | Yes| Notification parameter, which is used to display information in the notification bar.|
| request | [NotificationRequest](js-apis-notification.md#notificationrequest) | Yes| Notification parameter, which is used to display information in the notification bar.|
@@ -6,12 +6,14 @@ You can set your application to use the reminder agent APIs to create scheduled
...
@@ -6,12 +6,14 @@ You can set your application to use the reminder agent APIs to create scheduled
> **NOTE**
> **NOTE**
>
>
> This module is deprecated since API version 9. You are advised to use [@ohos.reminderAgentManager](js-apis-reminderAgentManager.md) instead.
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8).
Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8).
Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.|
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.|
**Return value**
**Return value**
| Type| Description|
| Type| Description|
| -------- | -------- |
| -------- | -------- |
| Promise<number> | Promise used to return the published reminder's ID.|
| Promise<number> | Promise used to return the published reminder's ID.|
**Example**
**Example**
```js
```js
...
@@ -89,7 +91,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba
...
@@ -89,7 +91,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba
| Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| reminderId | number | Yes| ID of the reminder to cancel.|
| reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).|
| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.|
| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.|
**Example**
**Example**
...
@@ -113,7 +115,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th
...
@@ -113,7 +115,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th
| Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| reminderId | number | Yes| ID of the reminder to cancel.|
| reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).|
**Return value**
**Return value**
...
@@ -453,10 +455,10 @@ Defines the reminder to publish.
...
@@ -453,10 +455,10 @@ Defines the reminder to publish.
| Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| reminderType | ReminderType | Yes| Type of the reminder.|
| reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.|
| actionButton | [ActionButton?, ActionButton?] | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)|
| actionButton | [ActionButton](#actionbutton) | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)|
| wantAgent | WantAgent | No| Information about the ability that is redirected to when the notification is clicked.|
| wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the notification is clicked.|
| maxScreenWantAgent | MaxScreenWantAgent | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.|
| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.|
| ringDuration | number | No| Ringing duration.|
| ringDuration | number | No| Ringing duration.|
| snoozeTimes | number | No| Number of reminder snooze times.|
| snoozeTimes | number | No| Number of reminder snooze times.|
| timeInterval | number | No| Reminder snooze interval.|
| timeInterval | number | No| Reminder snooze interval.|
The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent.
You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits.
> **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.
Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.|
**Error codes**
For details about the error codes, see [reminderAgentManager Error Codes](../errorcodes/errorcode-reminderAgentManager.md).
| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.|
**Error codes**
For details about the error codes, see [reminderAgentManager Error Codes](../errorcodes/errorcode-reminderAgentManager.md).
| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.|
| abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.|
## MaxScreenWantAgent
Provides the information about the target package and ability to start automatically when the reminder is displayed in full-screen mode. This API is reserved.
| reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.|
| actionButton | [ActionButton](#actionbutton) | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)|
| wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the notification is clicked.|
| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.|
| ringDuration | number | No| Ringing duration, in seconds.|
| snoozeTimes | number | No| Number of reminder snooze times.|
| timeInterval | number | No| Reminder snooze interval, in seconds.|
| title | string | No| Reminder title.|
| content | string | No| Reminder content.|
| expiredContent | string | No| Content to be displayed after the reminder expires.|
| snoozeContent | string | No| Content to be displayed when the reminder is snoozing.|
| notificationId | number | No| Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.|
| slotType | [notification.SlotType](js-apis-notification.md#slottype) | No| Type of the slot used by the reminder.|
The **BackgroundTaskManager** module provides APIs to manage background tasks.
If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension.
If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup.
If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task.
If a privileged system application needs to use certain system resources (for example, it wants to receive common events when suspended), it can request efficiency resources.
> **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.
Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 3 minutes when the battery level is higher than or equal to the broadcast low battery level and 1 minute when the battery level is lower than the broadcast low battery level.
| reason | string | Yes | Reason for delayed transition to the suspended state. |
| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.|
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. |
| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Error codes**
For details about the error codes, see [backgroundTaskManager Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md).
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. |
**Return value**
| Type | Description |
| -------------- | ---------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [backgroundTaskManager Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md).
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Error codes**
For details about the error codes, see [backgroundTaskManager Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md).
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
**Return value**
| Type | Description |
| -------------- | ---------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [backgroundTaskManager Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md).
A process and its application can request the same type of resources at the same time, for example, CPU resources. When the application releases the resources, the same type of resources requested by the process are also released.
| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes | Necessary information carried in the request, including the resource type and timeout interval. For details, see [EfficiencyResourcesRequest](#efficiencyresourcesrequest).|
**Error codes**
For details about the error codes, see [backgroundTaskManager Error Codes](../errorcodes/errorcode-backgroundTaskMgr.md).
| ID | Error Message |
| ---- | --------------------- |
| 9800001 | Memory operation failed. |
| 9800002 | Parcel operation failed. |
| 9800003 | IPC failed. | |
| 9800004 | System service operation failed. |
| 18700001 | Caller information verification failed when applying for efficiency resources. |
| requestId | number | Yes | ID of the suspension delay request. |
| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.<br>The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.|
| resourceTypes | number | Yes | Type of the resource to request. |
| isApply | boolean | Yes | Whether the request is used to apply for resources. The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources. |
| timeOut | number | Yes | Duration for which the resource will be used, in milliseconds. |
| isPersist | boolean | No | Whether the resource is permanently held. If the value is **true**, **timeOut** is invalid. |
| isProcess | boolean | No | Whether the request is initiated by a process. The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. |
| reason | string | Yes | Reason for requesting the resource. |
This module provides APIs for collecting statistics on device usage.
System applications can call these APIs to implement the following features:
- Query the usage duration in different time segments, events (foreground, background, start and end of continuous tasks), and the number of notifications, on a per application basis.
- Query statistics about system events (sleep, wakeup, unlock, and screen lock).
- Query the bundle group information of applications, including the invoking application itself.
- Query the idle status of applications, including the invoking application itself.
- Set the bundle group for other applications.
- Register and deregister the callback for application group changes.
Third-party applications can call these APIs to implement the following features:
- Query the idle status of the invoking application itself.
- Query the bundle group information of the invoking application itself.
- Query the events of the invoking application itself.
> **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.
>
## Modules to Import
```
import usageStatistics from '@ohos.resourceschedule.usageStatistics'
Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. A third-party application can only check the idle status of itself.
| bundleName | string | Yes | Bundle name of the application. |
| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the specified **bundleName** is valid, the idle state of the application is returned; otherwise, **null** is returned.|
**Error codes**
For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md).
Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. A third-party application can only check the idle status of itself.
| Promise<boolean> | Promise used to return the result. If the specified **bundleName** is valid, the idle state of the application is returned; otherwise, **null** is returned.|
**Error codes**
For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md).
Queries the application usage duration statistics based on the specified start time and end time. This API uses an asynchronous callback to return the result.
Queries the application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually). This API uses an asynchronous callback to return the result.
Queries the application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually). This API uses a promise to return the result.
| maxNum | number | Yes | Maximum number of returned records. The maximum value is **1000**.|
| callback | AsyncCallback<Array<[HapModuleInfo](#hapmoduleinfo)>> | Yes | Callback used to return a maximum of **maxNum** FA usage records.|
**Error codes**
For details about the error codes, see [DeviceUsageStatistics Error Codes](../errorcodes/errorcode-DeviceUsageStatistics.md).
Registers a callback for application group changes. When an application group of the user changes, an [AppGroupCallbackInfo](#appgroupcallbackinfo) instance is returned to all applications that have registered the callback. This API uses a promise to return the result.
Registers a callback for application group changes. When an application group of the user changes, an [AppGroupCallbackInfo](#appgroupcallbackinfo) instance is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.
Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time. This API uses a promise to return the result.
Queries the number of notifications from all applications based on the specified start time and end time. This API uses a promise to return the result.
Queries the number of notifications from all applications based on the specified start time and end time. This API uses an asynchronous callback to return the result.
| BY_OPTIMIZED | 0 | The system queries the application usage duration statistics in the specified time frame at the interval the system deems appropriate.|
| BY_DAILY | 1 | The system queries the application usage duration statistics in the specified time frame on a daily basis. |
| BY_WEEKLY | 2 | The system queries the application usage duration statistics in the specified time frame on a weekly basis. |
| BY_MONTHLY | 3 | The system queries the application usage duration statistics in the specified time frame on a monthly basis. |
| BY_ANNUALLY | 4 | The system queries the application usage duration statistics in the specified time frame on an annual basis. |
The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints.
The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
> **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.
> - For details about the restrictions, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks).
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
**Error codes**
For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
| ID | Error Message |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. |
**Example**
```js
try{
workScheduler.getWorkStatus(50,(error,res)=>{
if(error){
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
}else{
for(letiteminres){
console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
}
}
});
}catch(error){
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
}
```
## workScheduler.getWorkStatus:promise
getWorkStatus(workId: number): Promise\<WorkInfo>
Obtains the latest task status. This API uses a promise to return the result.
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; returns **null** otherwise.|
**Error codes**
For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
| ID | Error Message |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. |
**Example**
```js
try{
workScheduler.getWorkStatus(50).then((res)=>{
for(letiteminres){
console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
}
}).catch((error)=>{
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
})
}catch(error){
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
**Error codes**
For details about the error codes, see [workScheduler Error Codes](../errorcodes/errorcode-workScheduler.md).
| ID | Error Message |
| ---- | --------------------- |
| 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. |
**Example**
```js
try{
workScheduler.isLastWorkTimeOut(500)
.then(res=>{
console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
})
.catch(error=>{
console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
});
}catch(error){
console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
}
```
## WorkInfo
Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks).
Parcel operation failed. Failed to write the parcel.
**Description**
Failed to write the data object during the IPC.
**Possible Causes**
Failed to write the object.
**Solution**
Check whether the object value is normal.
## 10000003 System Service Operation Failure
**Error Message**
System service operation failed.
**Description**
The client process fails to obtain the system service.
**Possible Causes**
The dependent service process is faulty.
**Solution**
Try again later or restart the device.
## 10000004 IPC Failure
**Error Message**
IPC communication failed.
**Description**
The IPC fails.
**Possible Causes**
The system service is abnormal or the IPC data is abnormal.
**Solution**
Try again later or restart the device.
## 10000005 Application Not Installed
**Error Message**
The application is not installed.
**Description**
The application is not installed.
**Possible Causes**
The application is not installed or has been uninstalled.
**Solution**
Check whether the application exists.
## 10000006 Failed to Obtain Application Information
**Error Message**
Get application info failed.
**Description**
The client process fails to obtain application information from the service.
**Possible Causes**
1. The value of **beginTime** or **endTime** is invalid.
2. The application is not installed or has been uninstalled.
3. The value of **intervalType** is invalid.
**Solution**
Check whether the input parameters are valid and whether the application exists.
## 10000007 Time Operation Failure
**Error Message**
Get system or actual time operation failed.
**Description**
The system service fails to obtain the system time.
**Possible Causes**
The system is abnormal.
**Solution**
Try again later or restart the device.
## 10100001 Duplicate Application Group Operation
**Error Message**
Application group operation failed. The application group are the the same or do not need te be updated.
**Description**
Operating the application group, for example, setting an application group or registering or deregistering a callback for application group changes, fails.
**Possible Causes**
The application group to set already exists, or the callback for application group changes to register or deregister has already been registered or deregistered.
**Solution**
Do not repeatedly set application groups, or register or deregister a callback for application group changes.
## 10100002 Failed to Obtain Application Group Information
**Error Message**
Get application group info failed. The application group infomation cannot be found.
**Description**
The client process fails to obtain the application group information.
**Possible Causes**
1. An incorrect bundle name is passed.
2. The application is not installed or has been uninstalled.
**Solution**
Check whether the bundle name is valid and whether the application exists.
The application is not allowed to send notifications when **publishReminder()** is called.
**Possible Causes**
1. The application has not requested notification to be enabled.
2. The reminder function is disabled.
**Solution**
1. Call [Notification.requestEnableNotification](../apis/js-apis-notification.md#notificationrequestenablenotification8) to request notification to be enabled for the application.
2. Check whether the notification function is disabled.
## 1700002 Too Many Reminders
**Error Message**
The number of reminders exceeds the limit.
**Description**
The number of reminders exceeds the limit when **publishReminder()** is called.
**Possible Causes**
1. There are already 2000 reminders for the entire system.
2. There are already 30 reminders for the application.
**Solution**
Delete unnecessary reminders.
## 1700003 Nonexistent Reminder
**Error Message**
The reminder does not exist.
**Description**
The reminder passed in **cancelReminder()** does not exist.
You can set your application to call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits.
## Available APIs
**reminderAgentManager** encapsulates the APIs for publishing and canceling reminders.
For details about the APIs, see [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md).
**Table 1** Major APIs in reminderAgentManager
| Name| Description|
| -------- | -------- |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void<br>publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. |
| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void<br>cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)|
| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void<br>getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application.|
| cancelAllReminders(callback: AsyncCallback<void>): void<br>cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application.|
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void<br>addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder.|
| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void<br>removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type.|
## How to Develop
> **NOTE**
>
> 1. To publish a reminder through the reminder agent, your application must apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission.
>2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8).
> 3. The reminder agent can be used only after being authorized by the user.
According to the OpenHarmony background activity specifications, a third-party application will be suspended if it does not execute background tasks after switching to the background. In practice, an application may need to process certain work at specified moments, no matter what state it is in. For example, a shopping application needs to remind users of flash sale activities at some time points. Generally, a timer is used to achieve the preceding scenario. When the timer expires, the system starts the application to execute the task. However, some applications abuse the timer mechanism so they can be frequently waken up when running in the background. To avoid malicious background activities and meet service requirements of applications, OpenHarmony introduces the agent-powered scheduled reminder.
With the agent-powered scheduled reminder, the timing and pop-up notification functions of an application will be taken over by the reminder agent in the background, even when the application is suspended or exits. This prevents an application from being frequently woken up and helps reduce power consumption.
## Notification Instance Types
-**Countdown timers**: Applications can use this type to implement short-time timing notification services.
-**Calendar events**: Applications can use this type to implement long-time notification services.
-**Alarm clocks**: Applications can use this type to implement alarm-related services.
Frequent activities of background applications cause user devices to consume power quickly and respond slowly. To meet performance and power consumption requirements, the system allows applications to execute only activities within the specifications in the background. Activities beyond the specifications are suspended by default, and resources allocated to them will be reclaimed when the available resources are insufficient.
Frequent activities of background applications cause user devices to consume power quickly and respond slowly. To meet performance and power consumption requirements, the system allows applications in the background to execute only activities within the specifications. Activities beyond the specifications are suspended by default, and resources allocated to them will be reclaimed when the available resources are insufficient.
If an application or a service module running in the background has a service to continue, it can request a [transient task](#transient-tasks) to delay the suspension or a [continuous task](#continuous-tasks) to prevent the suspension. If an application needs to execute a non-real-time task when running in the background, it can request a [Work Scheduler Task](#work-scheduler-tasks). A privileged application can also request [efficiency resources](#efficiency-resources) for more flexibility.
## Background Task Types
## Background Task Types
Background tasks described in this document refer to the services that need to be continued when the respective applications or service modules are running in the background (not visible to the users). For more targeted management of background applications and service modules, OpenHarmony classifies applications and service modules into the following types:
For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode:
-**No background task**: An application or service module does not need further processing when switched to the background.
**No background task**: An application or service module does not need further processing when switched to the background.
-**Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task to delay the suspension.
**Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension.
-**Continuous task**: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP.
**Continuous task**: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP.
-**Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including CPU, WORK_SCHEDULER, software, and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended.
**Work Scheduler task**: The Work Scheduler provides a mechanism for applications to execute non-real-time tasks when the system is idle. If the preset conditions are met, the tasks will be placed in the execution queue and scheduled when the system is idle.
**Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including CPU, WORK_SCHEDULER, software, and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and the WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended.
@@ -64,10 +70,45 @@ OpenHarmony provides 9 background modes for services that require continuous tas
...
@@ -64,10 +70,45 @@ OpenHarmony provides 9 background modes for services that require continuous tas
- If a requested continuous task is not actually executed, the system will suspend the task once it detects the issue.
- If a requested continuous task is not actually executed, the system will suspend the task once it detects the issue.
- Each ability can request only one continuous task at a time.
- Each ability can request only one continuous task at a time.
## Work Scheduler Tasks
The Work Scheduler provides a mechanism for an application to execute a non-real-time task, for example, data learning, when the system is idle. The system places the Work Scheduler tasks requested by applications in a queue and determines the optimal scheduling time of each task based on the storage space, power consumption, temperature, and more. Persistence is supported. This means that a requested Work Scheduler task can be triggered when the application exits or the device restarts.
### Restrictions on Using Work Scheduler Tasks
The use of the Work Scheduler must comply with the following restrictions and rules:
-**Timeout**: The Work Scheduler callback can run only within the specified period of time. After the timeout, the callback automatically stops. The default timeout duration is 2 minutes. System applications can request [efficiency resources](efficiency-resources-apply-dev-guide.md) to obtain a longer duration (20 minutes in the charging state and 10 minutes in the non-charging state).
-**Execution frequency**: The system controls the execution frequency of Work Scheduler tasks based on the activity level of their respective applications. If an application has applied for the WORK_SCHEDULER resources through the efficiency resource API, the execution frequency is not limited within the validity period of the resources.
| Application Group | Work Scheduler Task Execution Frequency |
| Used every day| At a minimum interval of 4 hours|
| Frequently used| At a minimum interval of 24 hours|
| Infrequently used| At a minimum interval of 48 hours|
| Restricted| Prohibited|
| Unused| Prohibited|
| [Exemption group for efficiency resources](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | Unlimited|
-**WorkInfo setting**
-**workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the name of the current application. Otherwise, the verification will fail.
- At least one condition must be set.
- The repeat interval must be at least 20 minutes and must work with the Always repeat pattern or repeat times.
- The carried parameters can be of the number, string, or boolean type.
## Efficiency Resources
## Efficiency Resources
Efficiency resources are classified into CPU, WORK_SCHEDULER, software, and hardware resources.
Efficiency resources are classified into CPU, WORK_SCHEDULER, software, and hardware resources.
An application or process is assigned the privileges associated with the obtained efficiency resources. For example, with the CPU resources, the application or process will not be suspended. With the WORK_SCHEDULER resources, the application or process has more time to execute a task and is not restricted by the execution frequency. With the software and hardware resources, related resources are not proxied when the application or process is suspended.
An application or process is assigned the privileges associated with the obtained efficiency resources.
* With the CPU resources, the application or process will not be suspended.
* With the WORK_SCHEDULER resources, the application or process has more time to execute a task and is not restricted by the execution frequency.
* With the COMMON_EVENT resources, the application can still receive common events when it is suspended in the background.
* With the TIMER resources, the application can use the timer to execute precise scheduled tasks.
* With the hardware resources, the application can still be woken up by related services to execute tasks when it is suspended in the background.
**Table 2** Efficiency resource types
**Table 2** Efficiency resource types
...
@@ -83,5 +124,11 @@ An application or process is assigned the privileges associated with the obtaine
...
@@ -83,5 +124,11 @@ An application or process is assigned the privileges associated with the obtaine
### Restrictions on Using Efficiency Resources
### Restrictions on Using Efficiency Resources
- Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application.
- Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application.
- If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released.
- If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released.
- The WORK_SCHEDULER resources can be requested and released by applications, but not by processes.
- The WORK_SCHEDULER resources can be requested and released by applications, but not by processes.
- To use efficiency resources, an application must first submit a request to the application center to obtain corresponding privileges.
If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension. The application can also request efficiency resources in the following scenarios for more flexibility:
If an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP.
There is no time limit for a continuous task running in the background. To prevent abuse, the system limits the number of continuous tasks that can be requested. It also attaches a notification to the task so that the task is perceivable. In addition, the system verifies whether the application is actually executing the continuous task.
- The application should not be suspended within a period of time until it finishes the task.
## Available APIs
- The application requires system resources even when it is suspended. For example, an alarm clock requires timer resources even when being suspended.
**Table 1** Main APIs for continuous tasks
- The application needs to execute the task at an unlimited frequency and within a longer time.
| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo)| Requests delayed suspension after the application switches to the background.<br>The default duration value of delayed suspension is 180000 when the battery level is normal and 60000 when the battery level is low.|
| getRemainingDelayTime(requestId: number): Promise<number> | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the result. |
| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. |
### How to Develop
1. Request a suspension delay.
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspension delay will time out.");
});
var id = delayInfo.requestId;
console.info("requestId is: " + id);
```
2. Obtain the remaining duration before the application is suspended.
```js
backgroundTaskManager.getRemainingDelayTime(id).then( res => {
1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission and background mode type in the **config.json** file, with the ability type set to **service**.
If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources.
Development on the stage model:
If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks.
1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission and background mode type in the **module.json5** file.
1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission (**ohos.permission.KEEP_BACKGROUND_RUNNING**) and background mode type in the **config.json** file, with the ability type set to **service**.
For details about how to use the Service ability in the FA model, see [Service Ability Development](../ability/fa-serviceability.md).
If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources.
2. Call the APIs for requesting and canceling a continuous task in the Service ability.
If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks.
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
}
asyncfunctionprocessAsyncJobs(){
asyncfunctionprocessAsyncJobs(){
...
@@ -368,16 +177,128 @@ export default {
...
@@ -368,16 +177,128 @@ export default {
};
};
```
```
Development on the stage model:
### Development on the Stage Model
For details about the stage model, see [Stage Model Overview](../ability/stage-brief.md).
For details about the stage model, see [Stage Model Overview](../ability/stage-brief.md).
If an application needs to run a continuous task in the background, you can use **Call** to create and run an ability in the background. For details, see [Call Development](../ability/stage-call.md).
1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission (ohos.permission.KEEP_BACKGROUND_RUNNING) and background mode type in the **module.json5** file.
2. If an application needs to execute a continuous task for its own, include the execution logic in the Page ability. This is because an application cannot use **startAbilityByCall** to create and run its own ability in the background due to the restriction of ability startup controls. For details about how to use an ability in the stage model, see [Ability Development](../ability/stage-ability.md).
// Cancel the continuous task by clicking a button.
this.stopContinuousTask();
})
}
.width('100%')
}
.height('100%')
}
}
```
3. If a continuous task needs to be executed in the background for another application or on another device, you can create and run an ability in the background in Call mode. For details, see [Call Development](../ability/stage-call.md).
To further balance power consumption overhead of the system, privileged system applications can be suspended in the background as other applications. To ensure normal provisioning of important functions, efficiency resource APIs are provided for these applications so that they can execute special tasks and use specific system resources in the background. For example, if they want to receive common events when suspended, they can use the APIs to request the common event resources.
To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions.
By default, an application can run for 6 to 12 seconds after it switches to the background but before being suspended. If an application requires more time to execute an important task, it can call the **requestSuspendDelay** API to delay the suspension.
It is recommended that an application calls the **requestSuspendDelay** API before executing any time-consuming task, rather than when it is already running in the background.
The calling of the **requestSuspendDelay** API when the application is running in the foreground does not affect the transient task quota of the application.
Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should cancel the transient task in a timely manner.
Typical time-consuming tasks include saving status data to the local database, opening and processing a large file, and synchronizing data to the cloud server.
| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.<br>The default duration value of delayed suspension is 3 minutes when the battery level is normal and 1 minute when the battery level is low.|
| getRemainingDelayTime(requestId: number): Promise<number> | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the result. |
| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. |
## How to Develop
1. When an application needs to execute a time-consuming task, call the API to request a transient task. After the time-consuming task finishes execution, call the API to cancel the transient task.
console.info("Request suspension delay will time out.");
// The callback in invoked to notify the application that the suspension delay request is about to time out. The application needs to perform some cleanup and annotation operations.
});
id=delayInfo.requestId;
console.info("requestId is: "+id);
}
// Obtain the remaining duration before the application is suspended.
If your application needs to execute a non-real-time task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. For details about the constraints on the Work Scheduler usage, see [Work Scheduler Overview](./work-scheduler-overview.md).
If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
## Available APIs
## Available APIs
Import the **workScheduler** package to implement registration:
```js
importworkSchedulerfrom'@ohos.workScheduler';
```
Import the **WorkSchedulerExtensionAbility** package to implement callback:
startWork(work: WorkInfo): boolean | Starts a Work Scheduler task.
startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
stopWork(work: WorkInfo, needCancel?: boolean): boolean | Stops a Work Scheduler task.
stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a Work Scheduler task.
getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void | Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result.
getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result.
getWorkStatus(workId: number): Promise\<WorkInfo> | Obtains the status of a Work Scheduler task. This API uses a promise to return the result.
getWorkStatus(workId: number): Promise\<WorkInfo>; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result.
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo> | Obtains Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>> | Obtains Work Scheduler tasks. This API uses a promise to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): boolean; | Stops and clears Work Scheduler tasks.
stopAndClearWorks(): void;| Stops and clears Work Scheduler tasks.
isLastWorkTimeOut(workId: number, callback: AsyncCallback\<void>): boolean | Checks whether the last execution of the specified task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.
isLastWorkTimeOut(workId: number, callback: AsyncCallback\<void>): boolean;| Checks whether the last execution of the specified task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.
isLastWorkTimeOut(workId: number): Promise\<boolean> | Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.
isLastWorkTimeOut(workId: number): Promise\<boolean>;| Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.
**Table 2** WorkInfo parameters
**Table 2** WorkInfo parameters
> **NOTE**
For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
>
> For details about the constraints on configuring **WorkInfo**, see [Work Scheduler Overview](./work-scheduler-overview.md).
2. Develop an Extension ability to execute a Work Scheduler task. For details about the Extension ability, see [ExtensionAbility Mechanism](../ability/stage-brief.md#extensionability-mechanism).
The Work Scheduler provides a mechanism for applications to execute non-real-time tasks when the system is idle. If the preset conditions are met, the tasks will be placed in the execution queue and scheduled when the system is idle.
## Usage
If your application needs to execute a non-real-time task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met.
## Constraints
The use of the Work Scheduler must comply with the following restrictions and rules:
-**Timeout**: The Work Scheduler callback can run only within the specified period of time. After the timeout, the callback automatically stops.
-**Execution frequency**: The system controls the execution frequency of Work Scheduler tasks based on the activity level of their respective applications.
Application Group | Work Scheduler Task Execution Frequency
--------------------|-------------------------
Active| At a minimum interval of 2 hours
Used every day| At a minimum interval of 4 hours
Frequently used| At a minimum interval of 24 hours
Infrequently used| At a minimum interval of 48 hours
Restricted| Prohibited
Unused| Prohibited
-**WorkInfo setting**
-**workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the name of the current application. Otherwise, the verification will fail.
- At least one condition must be set.
- The repeat interval must be at least 20 minutes and must work with the Always repeat pattern or repeat times.
- The carried parameters can be of the number, string, or bool type.