提交 969e2e43 编写于 作者: W wusongqing 提交者: Gitee

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

Signed-off-by: Nwusongqing <wusongqing@huawei.com>
......@@ -81,16 +81,17 @@ You can set a USB device as the USB host to connect to other USB devices for dat
number: 1,
type: 3,
interfaceId: 0,
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
*/
```
2. Obtain the device operation permissions.
......
......@@ -17,7 +17,7 @@ Reference: [Notification](../reference/apis/js-apis-notification.md#notification
Example:
```ts
import WantAgent from '@ohos.wantAgent';
import WantAgent from '@ohos.app.ability.wantAgent';
async function publishNotification() {
let wantAgentInfo = {
......
......@@ -1864,7 +1864,7 @@ Obtains the area where this window cannot be displayed, for example, the system
| Name| Type| Mandatory| Description|
| ---- |----------------------------------| -- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.|
| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area. |
**Return value**
......@@ -2500,7 +2500,7 @@ Disables listening for window size changes.
| Name | Type | Mandatory| Description |
| -------- | ----------------------------- | ---- | -------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.|
| callback | Callback&lt;[Size](#size)&gt; | No | Callback used to return the window size. |
| callback | Callback&lt;[Size](#size7)&gt; | No | Callback used to return the window size. |
**Example**
......@@ -3006,7 +3006,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re
| Name| Type| Mandatory| Description|
| ---------- | ------------------------- | -- | ----------- |
| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.|
| colorSpace | [ColorSpace](#colorspace8) | Yes| Color space to set.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. |
**Error codes**
......@@ -3045,7 +3045,7 @@ Sets a color space for this window. This API uses a promise to return the result
| Name| Type| Mandatory| Description|
| ---------- | ------------------------- | -- | ------------- |
| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.|
| colorSpace | [ColorSpace](#colorspace8) | Yes| Color space to set.|
**Return value**
......@@ -3088,7 +3088,7 @@ Obtains the color space of this window.
| Type| Description|
| ------------------------- | ------------- |
| [ColorSpace](#colorspace) | Color space obtained.|
| [ColorSpace](#colorspace8) | Color space obtained.|
**Error codes**
......@@ -4631,7 +4631,7 @@ Obtains the area where this window cannot be displayed, for example, the system
| Name | Type | Mandatory | Description |
| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. |
| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. |
| callback | AsyncCallback&lt;[AvoidArea](#avoidarea7)&gt; | Yes | Callback used to return the area. |
**Example**
......@@ -4664,7 +4664,7 @@ Obtains the area where this window cannot be displayed, for example, the system
| Name | Type | Mandatory | Description |
| ---- | -------------------------------- | --------- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. |
| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. |
**Return value**
......@@ -5239,7 +5239,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re
| Name | Type | Mandatory | Description |
| ---------- | ------------------------- | --------- | ----------------------------------- |
| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. |
| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example**
......@@ -5271,7 +5271,7 @@ Sets a color space for this window. This API uses a promise to return the result
| Name | Type | Mandatory | Description |
| ---------- | ------------------------- | --------- | ------------------- |
| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. |
| colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. |
**Return value**
......@@ -5307,7 +5307,7 @@ Obtains the color space of this window. This API uses an asynchronous callback t
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;[ColorSpace](#colorspace)&gt; | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. |
| callback | AsyncCallback&lt;[ColorSpace](#colorspace8)&gt; | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. |
**Example**
......@@ -5338,7 +5338,7 @@ Obtains the color space of this window. This API uses a promise to return the re
| Type | Description |
| ---------------------------------------- | ----------------------------------------------- |
| Promise&lt;[ColorSpace](#colorspace)&gt; | Promise used to return the current color space. |
| Promise&lt;[ColorSpace](#colorspace8)&gt; | Promise used to return the current color space. |
**Example**
......
......@@ -74,7 +74,7 @@
- [Vibrator Error Codes](errorcode-vibrator.md)
- [System Parameter Error Codes](errorcode-system-parameterV9.md)
- [USB Error Codes](errorcode-usb.md)
- [Update Error Code](errorcode-update.md)
- [Update Error Codes](errorcode-update.md)
- Customization Management
- [Enterprise Device Management Error Codes](errorcode-enterpriseDeviceManager.md)
- Utils
......
# Time and Time Zone Service Error Codes
## -1 Screen Unlock Error
**Error Message**
The parameter check failed or permission denied or system error.
**Description**
This error code is reported when a parameter check failure, permission verification failure, or system operation error occurs.
**Possible Cause**
1. The input parameter is invalid.
2. The required permission is not configured. For example, **ohos.permission.SET_TIME** is not configured for setting the time or **ohos.permission.SET_TIME_ZONE** is not configured for setting the time zone.
3. The system is not running properly due to a common kernel error, such as a memory allocation and multi-thread processing error.
**Solution**
1. Make sure input parameters are passed in as required.
2. Configure the **ohos.permission.SET_TIME** permission for setting the time and the **ohos.permission.SET_TIME_ZONE** permission for setting the time zone.
3. Make sure the memory is sufficient.
......@@ -5,9 +5,9 @@
- [Transient Task Development](transient-task-dev-guide.md)
- [Continuous Task Development](continuous-task-dev-guide.md)
- [Work Scheduler Development](work-scheduler-dev-guide.md)
- [WorkSchedulerExtensionAbility Development](workscheduler-extensionability.md)
- [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md)
- Agent-Powered Scheduled Reminder
- [Agent-Powered Reminder Overview](reminder-agent-overview.md)
- [Agent-Powered Reminder Development](reminder-agent-development.md)
- [Agent-Powered Reminder Development](reminder-agent-development.md)
\ No newline at end of file
# Background Task Management Overview
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.
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
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 for delayed 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.
**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.
- **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.
- **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.
## Selecting a Background Task
![Background Task Selection](public_sys-resources/bgtask_choice.png)
![Background Task Selection](figures/bgtask_choice.png)
## Transient Tasks
......@@ -51,17 +51,17 @@ OpenHarmony provides 9 background modes for services that require continuous tas
**Table 1** Background modes for continuous tasks
| Background Mode| Description| Hint in Notification Panel| Remarks|
| -------- | -------- | -------- | -------- |
| dataTransfer | Data transfer through the network or peer device, such as download, backup, share, and transfer| A data transfer task is running.| - |
| audioPlayback | Audio output| An audio playback task is running.| - |
| audioRecording | Audio input| A recording task is running.| - |
| location | Positioning and navigation| A positioning task is running.| - |
| bluetoothInteraction | Bluetooth transmission| A Bluetooth-related task is running.| - |
| multiDeviceConnection | Distributed interconnection| A distributed task is running.| - |
| wifiInteraction | WLAN transmission| A WLAN-related task is running.| System API, which is available only to system applications|
| voip | Voice and video calls over VoIP| A call-related task is running.| System API, which is available only to system applications|
| taskKeeping | Computing task| A computing task is running| Effective only for specific devices|
| Background Mode | Description | Hint in Notification Panel | Remarks |
| --------------------- | ------------------------- | ------------ | ------------------------- |
| dataTransfer | Data transfer through the network or peer device, such as download, backup, share, and transfer| A data transfer task is running. | - |
| audioPlayback | Audio output | An audio playback task is running. | - |
| audioRecording | Audio input | A recording task is running. | - |
| location | Positioning and navigation | A positioning task is running. | - |
| bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - |
| multiDeviceConnection | Distributed interconnection | A distributed task is running. | - |
| wifiInteraction | WLAN transmission | A WLAN-related task is running.| System API, which is available only to system applications|
| voip | Voice and video calls over VoIP | A call-related task is running. | System API, which is available only to system applications|
| taskKeeping | Computing task | A computing task is running | Effective only for specific devices |
### Restrictions on Using Continuous Tasks
- If a user triggers a perceivable task, such as broadcasting and navigation, the corresponding background mode is triggered. When the task is started, the system forcibly displays a notification to the user.
......@@ -80,15 +80,15 @@ The use of the Work Scheduler must comply with the following restrictions and ru
- **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 |
| --------------------|------------------------- |
| 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|
| [Exemption group for efficiency resources](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | Unlimited|
| 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 |
| [Exemption group for efficiency resources](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#resourcetype)| Unlimited |
- **WorkInfo setting**
......@@ -110,25 +110,21 @@ An application or process is assigned the privileges associated with the obtaine
* 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
| Name | Value | Description |
| ----------------------- | ---- | --------------------- |
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. |
| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. |
| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. |
| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. |
| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. |
| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.|
| Name | Value | Description |
| -------------- | ---- | ------------------- |
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. |
| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. |
| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. |
| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. |
| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended.|
| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended. |
### 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.
- 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.
- To use efficiency resources, an application must first submit a request to the application center to obtain corresponding privileges.
<!--no_check-->
......@@ -3,7 +3,7 @@
## When to Use
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.
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 each of the tasks so that the tasks are perceivable. In addition, the system verifies whether the application is actually executing a continuous task.
## Available APIs
......@@ -15,7 +15,7 @@ There is no time limit for a continuous task running in the background. To preve
| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels the continuous task. |
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md).
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md).
**Table 2** Background modes
......@@ -34,152 +34,9 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA
## How to Develop
### Development on the FA Model
### Development in the Stage Model
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.
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 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**.
```
"module": {
"package": "com.example.myapplication",
"abilities": [
{
"backgroundModes": [
"dataTransfer",
"location"
], // Background mode
"type": "service" // The ability type is service.
}
],
"reqPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
2. Call the APIs for requesting and canceling a continuous task in the Service ability.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent';
import rpc from "@ohos.rpc";
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
let mMyStub;
class MyStub extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
console.log('ServiceAbility onRemoteRequest called');
// The meaning of code is user-defined.
if (code === 1) {
// Receive the request code for requesting a continuous task.
startContinuousTask();
// Execute the continuous task.
} else if (code === 2) {
// Receive the request code for canceling the continuous task.
stopContinuousTask();
} else {
console.log('ServiceAbility unknown request code');
}
return true;
}
}
export default {
onStart(want) {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
// Call the API to start the task.
startContinuousTask();
processAsyncJobs();
},
onStop() {
console.info('ServiceAbility onStop');
},
onConnect(want) {
console.info('ServiceAbility onConnect');
return mMyStub;
},
onReconnect(want) {
console.info('ServiceAbility onReconnect');
},
onDisconnect() {
console.info('ServiceAbility onDisconnect');
},
onCommand(want, restart, startId) {
console.info('ServiceAbility onCommand');
}
};
```
### 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 Development Overview](../application-models/stage-model-development-overview.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.
......@@ -201,10 +58,10 @@ For details about the stage model, see [Stage Model Overview](../ability/stage-b
}
```
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).
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, see [UIAbility Component Overview](../application-models/uiability-overview.md).
```ts
import wantAgent from '@ohos.wantAgent';
import wantAgent from '@ohos.app.ability.wantAgent';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
@Entry
......@@ -220,7 +77,7 @@ struct Index {
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility",
abilityName: "EntryAbility",
}
],
// Type of the operation to perform after the notification is clicked.
......@@ -290,14 +147,14 @@ struct Index {
}
```
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).
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 [Using Ability Call (Intra-Device)](../application-models/uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction) and [Using Ability Call (Inter-Device)](../application-models/hop-multi-device-collaboration.md#using-cross-device-ability-call).
```ts
import Ability from '@ohos.application.Ability'
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.wantAgent';
import wantAgent from '@ohos.app.ability.wantAgent';
const MSG_SEND_METHOD: string = 'CallSendMsg'
const MSG_SEND_METHOD: string = 'CallSendMsg';
let mContext = null;
......@@ -307,7 +164,7 @@ function startContinuousTask() {
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility",
abilityName: "EntryAbility",
}
],
// Type of the operation to perform after the notification is clicked.
......@@ -381,7 +238,7 @@ function sendMsgCallback(data) {
return new MySequenceable(10, "Callee test");
}
export default class BgTaskAbility extends Ability {
export default class BgTaskAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("[Demo] BgTaskAbility onCreate")
this.callee.on("test", sendMsgCallback);
......@@ -421,3 +278,146 @@ export default class BgTaskAbility extends Ability {
}
};
```
### Development in the FA Model
For details about how to use the ServiceAbility in the FA model, see [ServiceAbility Component Overview](../application-models/serviceability-overview.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.
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 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**.
```json
"module": {
"package": "com.example.myapplication",
"abilities": [
{
"backgroundModes": [
"dataTransfer",
"location"
], // Background mode
"type": "service" // The ability type is service.
}
],
"reqPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
2. Call the APIs for requesting and canceling a continuous task in the Service ability.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
let mMyStub;
class MyStub extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
console.log('ServiceAbility onRemoteRequest called');
// The meaning of code is user-defined.
if (code === 1) {
// Receive the request code for requesting a continuous task.
startContinuousTask();
// Execute the continuous task.
} else if (code === 2) {
// Receive the request code for canceling the continuous task.
stopContinuousTask();
} else {
console.log('ServiceAbility unknown request code');
}
return true;
}
}
export default {
onStart(want) {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
// Call the API to start the task.
startContinuousTask();
processAsyncJobs();
},
onStop() {
console.info('ServiceAbility onStop');
},
onConnect(want) {
console.info('ServiceAbility onConnect');
return mMyStub;
},
onReconnect(want) {
console.info('ServiceAbility onReconnect');
},
onDisconnect() {
console.info('ServiceAbility onDisconnect');
},
onCommand(want, restart, startId) {
console.info('ServiceAbility onCommand');
}
};
```
......@@ -5,16 +5,16 @@
The agent-powered reminder feature provides APIs for publishing background reminders. You can call these APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. The APIs are encapsulated in the [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md) class.
**Table 1** Major APIs in reminderAgentManager
**Table 1** Major APIs in reminderAgentManager
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | 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&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.) |
| getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application. |
| cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application. |
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder. |
| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback&lt;void&gt;): void<br>removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a **NotificationSlot** instance of a specified type. |
| API | Description |
| ---------------------------------------- | ---------------------------------------- |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | 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<br>and 2000 for the entire system.|
| cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)|
| getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application. |
| cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application. |
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder. |
| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback&lt;void&gt;): void<br>removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a **NotificationSlot** instance of a specified type. |
## How to Develop
......@@ -51,9 +51,9 @@ The agent-powered reminder feature provides APIs for publishing background remin
pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility'
},
title:'this is title', // Reminder title.
content:'this is content', // Reminder content.
expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires.
title: 'this is title', // Reminder title.
content: 'this is content', // Reminder content.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder.
}
......@@ -94,10 +94,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 5, // Reminder snooze interval, in seconds.
title:'this is title', // Reminder title.
title: 'this is title', // Reminder title.
content:'this is content', // Reminder content.
expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires.
snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
snoozeContent: 'remind later', // Content to be displayed when the reminder is snoozed.
notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder.
}
......@@ -131,10 +131,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 5, // Reminder snooze interval, in seconds.
title:'this is title', // Reminder title.
content:'this is content', // Reminder content.
expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires.
snoozeContent:'remind later', // Content to be displayed when the reminder is snoozed.
title: 'this is title', // Reminder title.
content: 'this is content', // Reminder content.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
snoozeContent: 'remind later', // Content to be displayed when the reminder is snoozed.
notificationId: 99, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder.
}
......@@ -175,7 +175,3 @@ The agent-powered reminder feature provides APIs for publishing background remin
console.log("cancelReminder code: " + error.code + ", message: " + error.message);
};
```
<!--no_check-->
\ No newline at end of file
......@@ -2,12 +2,11 @@
## When to Use
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.
By default, an application can run for a period of 6 to 12 seconds after it switches to the background. When this period expires, the application is suspended. If an application requires more time to execute an important task, it can call the **requestSuspendDelay** API to request a transient task 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.
You are advised not to call the [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) method to apply for delayed suspension after the application is running in the background. Instead, you need to call this interface to declare the execution time of the extended application to the system before performing any time-consuming operation. It is recommended that an application calls [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) when it is running in the foreground, so as not to 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.
An application can obtain the remaining duration before being suspended by calling [getRemainingDelayTime()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagergetremainingdelaytimecallback). Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should call [cancelSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagercancelsuspenddelay) to 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.
......@@ -19,67 +18,74 @@ Typical time-consuming tasks include saving status data to the local database, o
| API | Description |
| ---------------------------------------- | ---------------------------------------- |
| requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): [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.|
| requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo)| Requests delayed suspension after the application switches to the background.<br>The default duration 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&lt;number&gt; | 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.
When an application needs to execute a time-consuming task in the background, call the API to request a transient task. After the time-consuming task finishes execution, call the API to cancel the transient task.
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
let delayInfo;
let id;
let id; // ID of the suspension delay request.
let delayTime; // Remaining duration for the suspension delay request.
// Request a suspension delay.
function requestSuspendDelay() {
let myReason = 'test requestSuspendDelay';
delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
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.
});
let myReason = 'test requestSuspendDelay'; // Reason for the suspension delay request.
try {
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
// The callback is 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 and cancels the transient task.
console.info("[backgroundTaskManager] Request suspension delay will time out.");
backgroundTaskManager.cancelSuspendDelay(id);
})
id = delayInfo.requestId;
console.info("requestId is: " + id);
delayTime = delayInfo.actualDelayTime;
console.info("[backgroundTaskManager] The requestId is: " + id);
console.info("[backgroundTaskManager]The actualDelayTime is: " + delayTime);
} catch (error) {
console.error(`[backgroundTaskManager] requestSuspendDelay failed. code is ${error.code} message is ${error.message}`);
}
}
// Obtain the remaining duration before the application is suspended.
function getRemainingDelayTime() {
let delayTime = 0;
backgroundTaskManager.getRemainingDelayTime(id).then((res) => {
console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
delayTime = res;
}).catch((err) => {
console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
});
return delayTime;
async function getRemainingDelayTime() {
try {
await backgroundTaskManager.getRemainingDelayTime(id).then(res => {
console.log('[backgroundTaskManager] promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
}).catch(error => {
console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
})
} catch (error) {
console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
}
}
// Cancel the suspension delay.
function cancelSuspendDelay() {
backgroundTaskManager.cancelSuspendDelay(id);
backgroundTaskManager.cancelSuspendDelay(id);
}
function performingLongRunningTask() {
// Before executing the time-consuming task, call the API to request a transient task to delay the suspension.
requestSuspendDelay();
// Obtain the available time quota through the getRemainingDelayTime() API.
let delayTime = getRemainingDelayTime();
async function performingLongRunningTask() {
// Before executing a time-consuming task, call the API to request a transient task to delay the suspension.
requestSuspendDelay();
if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming operation.
// Handle the scenario where the time quota is insufficient.
// If required, obtain the available time quota through the getRemainingDelayTime() API.
await getRemainingDelayTime();
cancelSuspendDelay();
return;
}
if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming task.
// Handle the scenario where the time quota is insufficient.
cancelSuspendDelay();
return;
}
// Execute the time-consuming task.
// Execute the time-consuming task.
// After the time-consuming task is executed, call the API to cancel the transient task.
cancelSuspendDelay();
// After the time-consuming task is executed, call the API to cancel the transient task.
cancelSuspendDelay();
}
```
......@@ -2,7 +2,7 @@
## When to Use
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).
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. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks. For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
## Available APIs
......@@ -14,21 +14,21 @@ startWork(work: WorkInfo): void; | Starts 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): 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(): Promise<Array\<WorkInfo>>;| Obtains Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): void;| Stops and clears Work Scheduler tasks.
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains all the Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains all the Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): void;| Stops and clears all the 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): 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
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 restriction on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
Name| Type|Description
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
workId| number | Work ID. Mandatory.
bundleName| string | Name of the Work Scheduler task bundle. Mandatory.
abilityName| string | Name of the component to be notified by a Work Scheduler callback. Mandatory.
workId| number | ID of the Work Scheduler task. Mandatory.
bundleName| string | Bundle name of the Work Scheduler task. Mandatory.
abilityName| string | Name of the ability to be notified by a Work Scheduler callback. Mandatory.
networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.
isCharging| boolean | Whether the device is charging.
chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.
......@@ -42,26 +42,27 @@ parameters | {[key: string]: any} |Carried parameters.
**Table 3** Work Scheduler callbacks
Name | Description
API | Description
---------------------------------------------------------|-----------------------------------------
onWorkStart(work: WorkInfo): void | Triggered when the Work Scheduler task starts.
onWorkStop(work: WorkInfo): void | Triggered when the Work Scheduler task stops.
onWorkStart(work: WorkInfo): void | Called when the Work Scheduler task starts.
onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops.
### How to Develop
1. Import the modules.
Import the **workScheduler** package to implement registration:
```js
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
Import the **workScheduler** module.
```js
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
Import the **WorkSchedulerExtensionAbility** package to implement callback:
```js
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
Import the **WorkSchedulerExtensionAbility** module.
```js
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
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).
2. Develop an ExtensionAbility to execute a Work Scheduler task. For details about the ExtensionAbility, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md) and [WorkSchedulerExtensionAbility Development](./workscheduler-extensionability.md).
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
......@@ -77,7 +78,7 @@ export default class MyExtension extends WorkSchedulerExtensionAbility {
```
3. Register a Work Scheduler task.
3. Start a Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
......@@ -105,7 +106,7 @@ try{
```
4. Cancel the Work Scheduler task.
4. Stop the Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
......@@ -152,7 +153,7 @@ try{
```
6. Obtain all Work Scheduler tasks.
6. Obtain all the Work Scheduler tasks.
```ts
try{
......@@ -168,7 +169,7 @@ try{
}
```
7. Stop and clear Work Scheduler tasks.
7. Stop and clear all the Work Scheduler tasks.
```ts
try{
......@@ -179,7 +180,7 @@ try{
}
```
8. Check whether the last execution has timed out.
8. Check whether the last execution of a specified Work Scheduler task has timed out.
```ts
try{
......
# WorkSchedulerExtensionAbility Development
If your application needs to execute a non-real-time task or a persistent task, you can harness the Work Scheduler mechanism, which will schedule the task when the preset conditions (including the network type, charging type, storage status, battery status, and timing status) are met.
**WorkSchedulerExtensionAbility** provides callbacks for Work Scheduler tasks. When a Work Scheduler task starts or stops, these callbacks are invoked to process your service logic.
## Working Principles
Figure 1 shows the working principle of Work Scheduler.
**Figure 1** Work Scheduler working principle
![WorkSchedulerExtensionAbility](figures/WorkSchedulerExtensionAbility.png)
An application starts, stops, and obtains Work Scheduler tasks through the [workScheduler APIs](../reference/apis/js-apis-resourceschedule-workScheduler.md).
The application service layer detects and determines the conditions. If the preset conditions are met, the application service layer calls back the **WorkSchedulerExtensionAbility** object to start the application and triggers the **onWorkStart** and **onWorkStop** callbacks.
## Available APIs
The **WorkSchedulerExtensionAbility** class has the following APIs. For details, see [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md).
| Name| Description|
| -------- | -------- |
| onWorkStart(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task starts.|
| onWorkStop(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task stops.|
## How to Develop
To create a WorkScheduler project in DevEco Studio, perform the following steps:
- [Implement callbacks for Work Scheduler](#implementing-callbacks-for-work-scheduler): Develop the callbacks provided by **WorkSchedulerExtensionAbility**.
- [Implement Work Scheduler](#implementing-work-scheduler): Develop the [workScheduler APIs] to implement functions such as starting or stopping Work Scheduler tasks.
- [Set the configuration file](#setting-the-configuration-file): Set the configuration file **module.json5**.
### Implementing Callbacks for Work Scheduler
1. Create a module named **library** in the root directory of the project, with the **Ohos Library** template selected.
2. In the **./library/src/main/ets** directory under **library**, create an ArkTS file named **workAbility.ets** and implement the callbacks for Work Scheduler.
Import the module.
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
```
Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class workAbility extends WorkSchedulerExtensionAbility {
// Callback invoked when the Work Scheduler task starts.
onWorkStart(workInfo) {
console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`)
// Publish an upgrade notification.
let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, '')
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`)
}
console.log(`onWorkStart notification publish success`)
})
}
// Callback invoked when the Work Scheduler task stops.
onWorkStop(workInfo) {
// Publish an upgrade completion notification.
let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '')
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`)
}
console.log(`onWorkStop notification publish success`)
})
}
}
```
3. In the **./entry/src/main/ets** directory under the **entry** module of the project, create a directory named **workAbility**. In the **workAbility** directory, create an ArkTS file named **WorkTest.ets** and implement the callbacks for Work Scheduler.
Import the module.
```ts
import { workAbility } from '@ohos/library'
```
Inherit from **workAbility** and implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class WorkTest extends workAbility {
onWorkStart(workInfo) {
console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`)
super.onWorkStart(workInfo)
}
onWorkStopTest(workInfo) {
super.onWorkStop(workInfo)
console.log(`onWorkStop value`)
}
}
```
### Implementing Work Scheduler
1. In the **./library/src/main/ets** directory under **library**, create a TypeScript file named **DelayWork.ts**, and implement the Work Scheduler APIs.
Import the module.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler'
```
Encapsulate the APIs for starting and stopping Work Scheduler tasks.
```ts
export default class DelayWork {
private workInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: '',
abilityName: ''
}
// Start the Work Scheduler task.
startWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName
this.workInfo.abilityName = abilityName
try {
workScheduler.startWork(this.workInfo)
console.log(`startWork success`)
} catch (error) {
Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`)
prompt.showToast({
message: `${error.message}`
})
}
}
// Stop the Work Scheduler task.
stopWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName
this.workInfo.abilityName = abilityName
workScheduler.stopWork(this.workInfo, false)
console.log(`stopWork`)
}
}
```
2. In the **./entry/src/main/ets/pages/index.ets** directory under the **entry** module of the project, add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task.
Import the module.
```ts
import { workAbility } from '@ohos/library'
```
Add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task. In the API, **bundleName** and **abilityName** are passed in, where the value of **abilityName** is **WorkTest**.
```ts
Button($r('app.string.upgrade'))
.width('60%')
.height(40)
.fontSize(30)
.onClick(() => {
this.work.startWork('ohos.samples.workscheduler', 'WorkTest')
})
```
When the component is destructed, it calls the API to stop the Work Scheduler task.
```ts
aboutToDisappear() {
this.work.stopWork('ohos.samples.workscheduler', 'WorkTest')
}
```
### Setting the Configuration File
1. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEntrance** to the code path of the WorkSchedulerExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "WorkTest",
"srcEntrance": "./ets/workAbility/WorkTest.ets",
"label": "$string:WorkSchedulerExtensionAbility_label",
"description": "$string:WorkSchedulerExtensionAbility_desc",
"type": "workScheduler"
}
]
}
}
```
......@@ -47,30 +47,30 @@ You can create a subwindow, such as a dialog box, and set its properties.
- Call **window.createWindow** to create a subwindow.
- Call **window.findWindow** to find an available subwindow.
```js
import window from '@ohos.window';
```js
import window from '@ohos.window';
let windowClass = null;
// Method 1: Create a subwindow.
let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP, ctx: this.context};
window.createWindow(config, (err, data) => {
if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
// Method 2: Find a subwindow.
window.findWindow("subWindow", (err, data) => {
if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
```
let windowClass = null;
// Method 1: Create a subwindow.
let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP, ctx: this.context};
window.createWindow(config, (err, data) => {
if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
// Method 2: Find a subwindow.
window.findWindow("subWindow", (err, data) => {
if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
```
2. Set the properties of the subwindow.
......
# Utils FAQ<a name="EN-US_TOPIC_0000001058735275"></a>
## 1. Failed to run the KV store on the LiteOS Cortex-A kernel \(Hi3516 or Hi3518\) due to incorrect path setting for the KV store<a name="section2041345718513"></a>
**Symptom**
When the LiteOS Cortex-A kernel \(Hi3516 or Hi3518 platform\) directly calls the API provided by the KV store, the compiled executable program fails to run.
**Possible Causes**
The compiled executable program is run directly without being converted to an application using **AbilityKit** APIs. In this case, the Bundle Manager Service \(BMS\) cannot correctly set the path for storing application data during application installation. As a result, the KV store fails to run.
**Solution**
Call the **UtilsSetEnv** function of the KV store to set the data storage path.
```
UtilsSetEnv("/storage/com.example.kv");
```
# Utils Development<a name="EN-US_TOPIC_0000001059307279"></a>
## Available APIs<a name="section1633115419401"></a>
**Table 1** APIs for file operations
| Function | Description |
| ---------- | ------------- |
| int UtilsFileOpen(const char* path, int oflag, int mode) | Opens or creates a file. |
| int UtilsFileClose(int fd) | Closes a file with a specified file descriptor. |
| int UtilsFileRead(int fd, char *buf, unsigned int len) | Reads a specified length of data from a file with the specified file descriptor and writes the data into the buffer. |
| int UtilsFileWrite(int fd, const char *buf, unsigned int len) | Writes a specified length of data into a file with the specified file descriptor. |
| int UtilsFileDelete(const char *path) | Deletes a specified file. |
| int UtilsFileStat(const char *path, unsigned int *fileSize) | Obtains the file size. |
| int UtilsFileSeek(int fd, int offset, unsigned int whence) | Adjusts the read and write position offset in a file. |
| int UtilsFileCopy(const char* src, const char* dest) | Copies the source file to a target file. |
| int UtilsFileMove(const char* src, const char* dest) | Moves the source file into a target file. |
Sample code for file operations:
# Commonlibrary Development Guidelines<a name="EN-US_TOPIC_0000001059307279"></a>
## Overview
The **commonlibrary** subsystem stores basic OpenHarmony components which provides common enhanced APIs for development in C, C++ and JS that are commonly used by OpenHarmony service subsystems and upper-layer applications. Including repositories:
```
// Open a file and write data.
char fileName[] = "testfile";
static const char def[] = "utils_file_operation implement.";
int fd = UtilsFileOpen(fileName, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0);
printf("file handle = %d\n", fd);
int ret = UtilsFileWrite(fd, def, strlen(def));
printf("write ret = %d\n", ret);
// Adjust the position offset in the file.
ret = UtilsFileSeek(fd, 5, SEEK_SET_FS);
printf("lseek ret = %d\n", ret);
// Read data and close the file.
char buf[64] = {0};
int readLen = UtilsFileRead(fd, buf, 64);
ret = UtilsFileClose(fd);
printf("read len = %d : buf = %s\n", readLen, buf);
// Obtain the file size.
int fileLen = 0;
ret = UtilsFileStat(fileName, &fileLen);
printf("file size = %d\n", fileLen);
// Delete the file.
ret = UtilsFileDelete(fileName);
printf("delete ret = %d\n", ret);
```
**Table 2** APIs for KV store operations
| Function | Description |
| ----------- | ---------------- |
| int UtilsGetValue(const char* key, char* value, unsigned int len) | Obtains the value matching a specified key from the file system or cache. |
| int UtilsSetValue(const char* key, const char* value) | Adds or updates the value matching a specified key in the file system or cache. |
| int UtilsDeleteValue(const char* key) | Deletes the value matching a specified key from the file system or cache. |
Sample code for the KV store:
```
// Set the value matching the specified key.
char key[] = "rw.sys.version_100";
char value[] = "Hello kv operation implement!";
int ret = UtilsSetValue(key, value);
printf("UtilsSetValue set ret = %d\n", ret);
// Obtain the value matching the specified key.
char temp[128] = {0};
ret = UtilsGetValue(key, temp, 128);
printf("UtilsGetValue get ret = %d, temp = %s\n", ret, temp);
// Delete the value matching the specified key.
ret = UtilsDeleteValue(key);
printf("UtilsDeleteValue delete ret = %d\n", ret);
/commonlibrary
├── c_utils # Enhanced basic C/C++ library for developers
├── ets_utils # Enhanced basic JS library for developers
└── utils_lite # Basic tools for liteOS, including C and JS.
```
Features provided by every repositories are listed here:
## How to Develop<a name="section17450172710292"></a>
### Developing a Native Application for the KV Store That Uses the LiteOS Cortex-A Kernel \(Hi3516 or Hi3518\)<a name="section258354119295"></a>
1. Develop the native application for the KV store using **AbilityKit** APIs.
- Write the user program by calling the APIs provided by the KV store and compile the **libLauncher.so** file.
```
// Set the value matching the specified key.
char key[] = "rw.sys.version_100";
char value[] = "Hello kv operation implement!";
int ret = UtilsSetValue(key, value);
printf("UtilsSetValue set ret = %d\n", ret);
// Obtain the value matching the specified key.
char temp[128] = {0};
ret = UtilsGetValue(key, temp, 128);
printf("UtilsGetValue get ret = %d, temp = %s\n", ret, temp);
// Delete the value matching the specified key.
ret = UtilsDeleteValue(key);
printf("UtilsDeleteValue delete ret = %d\n", ret);
```
- Edit the **config.json** file as follows:
```
{
"app": {
"bundleName": "com.example.launcher",
"vendor": "example,
"version": {
"code": 1,
"name": "1.0"
}
},
"deviceConfig": {
"default": {
"reqSdk": {
"compatible": "zsdk 1.0.0",
"target": "zsdk 1.0.1"
},
"keepAlive": false
},
"smartCamera": {
"reqSdk": {
"compatible": "zsdk 1.0.0",
"target": "zsdk 1.0.1"
},
"keepAlive": false
}
},
"module": {
"package": "com.example.launcher",
"name": ".MyHarmonyAbilityPackage",
"deviceType": [
"phone", "tv","tablet", "pc","car","smartWatch","sportsWatch","smartCamera"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "Launcher",
"moduleType": "entry"
},
"abilities": [{
"name": "MainAbility",
"icon": "res/drawable/phone.png",
"label": "test app 1",
"launchType": "standard",
"type": "page"
},
{
"name": "SecondAbility",
"icon": "res/drawable/phone.png",
"label": "test app 2",
"launchType": "standard",
"type": "page"
},
{
"name": "ServiceAbility",
"icon": "res/drawable/phone.png",
"label": "test app 2",
"launchType": "standard",
"type": "service"
}
]
}
}
```
- Generate a HAP file.
- Add resource files in the **res/drawable** directory based on the following directory structure.
![](figure/unnaming.png)
- Compress the **libLauncher.so**, **config.json**, and resource files into a ZIP package and change the file name extension to **.hap**, for example, **Launcher.hap**.
2. Connect the development board and send the command for installing the native KV store application to the board through the serial port.
```
./nfs/dev_tools/bin/bm install -p /nfs/Launcher.hap
```
3. Send the command for running the native KV store application to the board through the serial port.
```
./nfs/dev_tools/bin/aa start -p com.example.launcher -n ServiceAbility
```
### Dumping System Attributes on the Platform That Uses the LiteOS Cortex-M Kernel<a name="section9179161863014"></a>
1. Connect the development board and send the **AT+SYSPARA** command to the board through the serial port.
```
AT+SYSPARA
```
**Figure 1** Output of the system attribute dumping command for the LiteOS Cortex-M kernel<a name="fig15179161863016"></a>
![](figure/output-of-the-system-attribute-dumping-command-for-the-liteos-cortex-m-kernel.png "output-of-the-system-attribute-dumping-command-for-the-liteos-cortex-m-kernel")
**c_utils**
- Enhanced APIs for operations related to files, paths, and strings
- APIs related to the read-write lock, semaphore, timer, thread, and thread pool
- APIs related to the security data container and data serialization
- Error codes for each subsystem
- Safe functions in C
### Dumping System Attributes on the Platform That Uses the LiteOS Cortex-A Kernel<a name="section3179121853017"></a>
**ets_utils**
1. Connect the development board and run the **os\_dump --help** command in the **bin** directory to view the **os\_dump** help information.
- JSAPIs for operation of URI, URL and xml
- JSAPIs for character encoder and decoder
- JSAPIs for operation of process
- Multithreading ability in JS
```
./bin/os_dump --help
```
**utils_lite**
2. Run the **os\_dump -l** command in the **bin** directory to view system modules that support attribute dumping.
- Hardware Abstraction Layer (HAL) APIs for performing operations on standard files
- APIs for internal functions, such as the timer
```
./bin/os_dump -l
```
## Development Guidelines<a name="section1633115419401"></a>
3. Run the **os\_dump syspara** command in the **bin** directory to dump the current system attributes.
[Development Guidelines for c_utils](https://gitee.com/openharmony/commonlibrary_c_utils/blob/master/docs/en/c-utils-guide.md)
```
./bin/os_dump syspara
```
**Figure 2** Output of the system attribute dumping command for the LiteOS Cortex-A kernel<a name="fig2179718143018"></a>
![](figure/output-of-the-system-attribute-dumping-command-for-the-liteos-cortex-a-kernel.png "output-of-the-system-attribute-dumping-command-for-the-liteos-cortex-a-kernel")
# Commonlibrary Subsystem FAQ
## c_utils FAQ
See [Development Guidelines for c_utils](https://gitee.com/openharmony/commonlibrary_c_utils/blob/master/docs/en/c-utils-guide.md), including FAQs for several scenarios.
\ No newline at end of file
# Utils Overview<a name="EN-US_TOPIC_0000001060172974"></a>
The Utils library stores basic OpenHarmony components that are commonly used by OpenHarmony service subsystems and upper-layer applications.
This library provides the following capabilities on different platforms:
- LiteOS Cortex-M \(Hi3861 platform\): KV store, file operations, IoT peripheral control, and system attribute dumping
- LiteOS Cortex-A \(Hi3516 or Hi3518 platform\): KV store, timer, JavaScript APIs for data and file storage, and system attribute dumping
......@@ -3,7 +3,14 @@
## Introduction<a name="section11660541593"></a>
The **commonlibrary** subsystem provides common enhanced APIs for development in C, C++ and JS.
The **commonlibrary** subsystem stores basic OpenHarmony components which provides common enhanced APIs for development in C, C++ and JS that are commonly used by OpenHarmony service subsystems and upper-layer applications. Including repositories:
```
/commonlibrary
├── c_utils # Enhanced basic C/C++ library for developers
├── ets_utils # Enhanced basic JS library for developers
└── utils_lite # Basic tools for liteOS, including C and JS.
```
Features provided by every repositories are listed here:
**c_utils**
......@@ -24,15 +31,8 @@ The **commonlibrary** subsystem provides common enhanced APIs for development in
- Hardware Abstraction Layer (HAL) APIs for performing operations on standard files
- APIs for internal functions, such as the timer
## Directory Structure<a name="section17271017133915"></a>
```
/commonlibrary
├── c_utils # Enhanced basic C/C++ library for developers
├── ets_utils # Enhanced basic JS library for developers
└── utils_lite # Basic tools for liteOS, including C and JS.
```
## Related Documents<a name="section17271017133915"></a>
[Commonlibrary Development Guidelines](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-utils-guide.md)
## Repositories Involved<a name="section1249817110914"></a>
......
......@@ -18,14 +18,14 @@ After change:
| Module | Class | Method/Attribute/Enumeration/Constant | Change Type|
| ----------------- | ----------- | ------------------------------------------------------------ | -------- |
| @ohos.systemTimer | systemTimer | function createTimer(options: TimerOptions, callback: AsyncCallback<number>): void | Changed |
| @ohos.systemTimer | systemTimer | function createTimer(options: TimerOptions): Promise<number> | Changed |
| @ohos.systemTimer | systemTimer | function startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function startTimer(timer: number, triggerTime: number): Promise<void> | Changed |
| @ohos.systemTimer | systemTimer | function stopTimer(timer: number, callback: AsyncCallback<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function stopTimer(timer: number): Promise<void> | Changed |
| @ohos.systemTimer | systemTimer | function destroyTimer(timer: number, callback: AsyncCallback<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function destroyTimer(timer: number): Promise<void> | Changed |
| @ohos.systemTimer | systemTimer | function createTimer(options: TimerOptions, callback: AsyncCallback\<number>): void | Changed |
| @ohos.systemTimer | systemTimer | function createTimer(options: TimerOptions): Promise\<number> | Changed |
| @ohos.systemTimer | systemTimer | function startTimer(timer: number, triggerTime: number, callback: AsyncCallback\<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function startTimer(timer: number, triggerTime: number): Promise\<void> | Changed |
| @ohos.systemTimer | systemTimer | function stopTimer(timer: number, callback: AsyncCallback\<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function stopTimer(timer: number): Promise\<void> | Changed |
| @ohos.systemTimer | systemTimer | function destroyTimer(timer: number, callback: AsyncCallback\<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function destroyTimer(timer: number): Promise\<void> | Changed |
**Adaptation Guide**
......@@ -34,232 +34,303 @@ Refer to the code below to capture errors when **systemTimer** APIs are called i
createTimer callback mode:
**Example**:
**Example**
```js
export default {
systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat: false
};
try {
systemTimer.createTimer(options, (error, data) => {
if (error) {
// Capture the permission denial error.
console.info(`Failed to create timer. message:${error.message}, code:${error.code}`);
}
});
} catch(e) {
// Capture the parameter verification error.
console.info(`Failed to create timer. message:${e.message}, code:${e.code}`);
systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat: false
};
try {
systemTimer.createTimer(options, (error, timerId) => {
if (error) {
// Capture the permission denial error.
console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
}
console.info(`Succeeded in creating timer. timerId: ${timerId}`);
});
} catch(e) {
// Capture the parameter verification error.
console.info(`Failed to create timer. message: ${e.message}, code: ${e.code}`);
}
}
}
```
createTimer promise mode:
**Example**:
**Example**
```js
export default {
systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat: false
};
try {
systemTimer.createTimer(options).then((data) => {
console.info(`Succeeded in creating timer. Data:` + data);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to create timer. message:${error.message}, code:${error.code}`);
});
} catch(e) {
// Capture the parameter verification error.
console.info(`Failed to create timer. message:${e.message}, code:${e.code}`);
}
systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat: false
};
try {
systemTimer.createTimer(options).then((timerId) => {
console.info(`Succeeded in creating timer. timerId: ${timerId}`);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
});
} catch(e) {
// Capture the parameter verification error.
console.info(`Failed to create timer. message: ${e.message}, code: ${e.code}`);
}
}
}
```
startTimer callback mode:
**Example**:
**Example**
```js
export default {
async systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
try {
systemTimer.startTimer(timerId, triggerTime, (error) => {
if (error) {
// Capture the permission denial error.
console.error(`Failed to start timer. message:${error.message}, code:${error.code}`);
}
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to start timer. message:${e.message}, code:${e.code}`);
async systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
try {
systemTimer.startTimer(timerId, triggerTime, (error) => {
if (error) {
// Capture the permission denial error.
console.error(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
}
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`);
}
}
}
```
startTimer promise mode:
**Example**:
**Example**
```js
export default {
async systemTimer (){
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
try {
systemTimer.startTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in startting timer. Data:` + data);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to start timer. message:${error.message}, code:${error.code}`);
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to start timer. message:${e.message}, code:${e.code}`);
}
async systemTimer (){
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
try {
systemTimer.startTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in startting timer. Data:` + data);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`);
}
}
}
```
stopTimer callback mode:
**Example**:
**Example**
```js
export default {
async systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
try {
systemTimer.stopTimer(timerId, triggerTime, (error) => {
if (error) {
// Capture the permission denial error.
console.error(`Failed to stop timer. message:${error.message}, code:${error.code}`);
}
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to stop timer. message:${e.message}, code:${e.code}`);
async systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
try {
systemTimer.stopTimer(timerId, triggerTime, (error) => {
if (error) {
// Capture the permission denial error.
console.error(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
}
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`);
}
}
}
}git
```
stopTimer promise mode:
**Example**:
**Example**
```js
export default {
async systemTimer (){
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
try {
systemTimer.stopTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in stop timer. Data:` + data);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to stop timer. message:${error.message}, code:${error.code}`);
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to stop timer. message:${e.message}, code:${e.code}`);
}
async systemTimer (){
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
try {
systemTimer.stopTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in stop timer. Data:` + data);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`);
}
}
}
```
destroyTimer callback mode:
**Example**:
**Example**
```js
export default {
async systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
systemTimer.stopTimer(timerId);
try {
systemTimer.destroyTimer(timerId, triggerTime, (error) => {
if (error) {
// Capture the permission denial error.
console.error(`Failed to destroy timer. message:${error.message}, code:${error.code}`);
}
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to destroy timer. message:${e.message}, code:${e.code}`);
async systemTimer () {
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
systemTimer.stopTimer(timerId);
try {
systemTimer.destroyTimer(timerId, triggerTime, (error) => {
if (error) {
// Capture the permission denial error.
console.error(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
}
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to destroy timer. message: ${e.message}, code: ${e.code}`);
}
}
}
```
destroyTimer promise mode:
**Example**:
**Example**
```js
export default {
async systemTimer (){
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
systemTimer.stopTimer(timerId);
try {
systemTimer.destroyTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in destroy timer. Data:` + data);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to destroy timer. message:${error.message}, code:${error.code}`);
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to destroy timer. message:${e.message}, code:${e.code}`);
}
async systemTimer (){
let options = {
type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false
}
let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime();
triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime);
systemTimer.stopTimer(timerId);
try {
systemTimer.destroyTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in destroy timer. Data:` + data);
}).catch((error) => {
// Capture the permission denial error.
console.info(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to destroy timer. message: ${e.message}, code: ${e.code}`);
}
}
}
```
## cl.time.2 API Error Change
Errors thrown by timer APIs of the time subsystem: **201** (permission denied), **202** (non-system application), and **401** (invalid parameters).
**Change Impacts**
Applications developed based on earlier versions can still use the APIs. When new APIs are used, errors must be captured and processed.
**Key API/Component Changes**
Before change:
- The API throws an error message with error code **-1**.
After change:
- The API throws an error message with an error code. Error code **201** indicates that the permission is denied, error code **202** indicates that the application is not a system application, and error code **401** indicates that the parameters are invalid.
Deprecated APIs can be replaced with new ones with same names.
| Original API | New API |
| ---------------- | -------------------- |
| @ohos.systemTime | @ohos.systemDateTime |
**Adaptation Guide**
Refer to the code below to capture errors when **systemTime** APIs are called in applications. In the examples, the **setTime** API is invoked.
In callback mode:
**Example**
```js
import systemDateTime from @ohos.systemDateTime
// Set the system time to 2021-01-20 02:36:25.
let time = 1611081385000;
try {
systemDateTime.setTime(time, (error) => {
// Capture permission denial and non-system-application errors.
if (error) {
console.info(`Failed to setting time. message: ${error.message}, code: ${error.code}`);
return;
}
console.info(`Succeeded in setting time.`);
})
} catch(e) {
// Capture the parameter verification error.
console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`);
}
```
In promise mode:
**Example**
```js
import systemDateTime from @ohos.systemDateTime
// Set the system time to 2021-01-20 02:36:25.
let time = 1611081385000;
try {
systemDateTime.setTime(time).then(() => {
console.info(`Succeeded in setting time.`);
}).catch((error) => {
// Capture permission denial and non-system-application errors.
console.info(`Failed to setting time. message: ${error.message}, code: ${error.code}`);
});
} catch(e) {
// Capture the parameter verification error.
console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`);
}
```
......@@ -69,6 +69,7 @@
- [Native API的相关指导](napi/Readme-CN.md)
- 工具
- [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.md)
- [调试工具](tools/Readme-CN.md)
- 示例教程
- [示例代码](https://gitee.com/openharmony/applications_app_samples/blob/master/README_zh.md)
- [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md)
......
......@@ -60,13 +60,7 @@
} catch (error) {
console.info(`explicit start ability failed with ${error.code}`)
}
let context = getContext(this) as common.UIAbilityContext;
await context.startAbility(want)
console.info(`explicit start ability succeed`)
} catch (error) {
console.info(`explicit start ability failed with ${error.code}`)
}
}
}
```
匹配过程如下:
......
......@@ -67,7 +67,7 @@
- [获取应用开发路径](#获取应用开发路径)
- [获取和修改加密分区](#获取和修改加密分区)
- [创建其他应用或其他Module的Context](#创建其他应用或其他module的context)
- [订阅进程内Ability生命周期变化](#订阅进程内ability生命周期变化)
- [订阅进程内UIAbility生命周期变化](#订阅进程内uiability生命周期变化)
### 获取应用开发路径
......@@ -106,12 +106,12 @@
| 属性 | 路径 |
| -------- | -------- |
| bundleCodeDir | {路径前缀}/el1/bundle/ |
| cacheDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**cache/ |
| filesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**files/ |
| preferencesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**preferences/ |
| tempDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**temp/ |
| databaseDir | {路径前缀}/{加密等级}/database/**{moduleName}/** |
| distributedFilesDir | {路径前缀}/el2/distributedFiles/**{moduleName}/** |
| cacheDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/cache/ |
| filesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/files/ |
| preferencesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/preferences/ |
| tempDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/temp/ |
| databaseDir | {路径前缀}/{加密等级}/database/**{moduleName}**/ |
| distributedFilesDir | {路径前缀}/el2/distributedFiles/**{moduleName}**/ |
获取应用开发路径的示例代码如下所示。
......@@ -133,6 +133,9 @@ export default class EntryAbility extends UIAbility {
}
```
> **说明:**
>
> 示例代码获取到的是应用开发路径的沙箱路径。其对应的绝对路径,在创建或者修改文件之后,可以在`hdc shell`中,通过`find / -name <文件名称>`命令查找获取。
### 获取和修改加密分区
......@@ -226,11 +229,11 @@ export default class EntryAbility extends UIAbility {
```
### 订阅进程内Ability生命周期变化
### 订阅进程内UIAbility生命周期变化
在应用内的DFX统计场景,如需要统计对应页面停留时间和访问频率等信息,可以使用订阅进程内Ability生命周期变化功能。
在应用内的DFX统计场景,如需要统计对应页面停留时间和访问频率等信息,可以使用订阅进程内UIAbility生命周期变化功能。
在进程内Ability生命周期变化时,如创建、可见/不可见、获焦/失焦、销毁等,会触发进入相应的回调,其中返回的此次注册监听生命周期的ID(每次注册该ID会自增+1,当超过监听上限数量2^63-1时,返回-1),以在[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md)中使用为例进行说明。
[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext)提供了订阅进程内UIAbility生命周期变化的能力。在进程内UIAbility生命周期变化时,如创建、可见/不可见、获焦/失焦、销毁等,会触发进入相应的回调,其中返回的此次注册监听生命周期的ID(每次注册该ID会自增+1,当超过监听上限数量2^63-1时,返回-1),以在[UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md)中使用为例进行说明。
```ts
......@@ -244,36 +247,36 @@ export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
let abilityLifecycleCallback = {
onAbilityCreate(ability) {
console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability));
onAbilityCreate(uiability) {
console.info(TAG, "onAbilityCreate uiability:" + JSON.stringify(uiability));
},
onWindowStageCreate(ability, windowStage) {
console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability));
onWindowStageCreate(uiability, windowStage) {
console.info(TAG, "onWindowStageCreate uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
},
onWindowStageActive(ability, windowStage) {
console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability));
onWindowStageActive(uiability, windowStage) {
console.info(TAG, "onWindowStageActive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageInactive(ability, windowStage) {
console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability));
onWindowStageInactive(uiability, windowStage) {
console.info(TAG, "onWindowStageInactive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
},
onWindowStageDestroy(ability, windowStage) {
console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability));
onWindowStageDestroy(uiability, windowStage) {
console.info(TAG, "onWindowStageDestroy uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
},
onAbilityDestroy(ability) {
console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability));
onAbilityDestroy(uiability) {
console.info(TAG, "onAbilityDestroy uiability:" + JSON.stringify(uiability));
},
onAbilityForeground(ability) {
console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability));
onAbilityForeground(uiability) {
console.info(TAG, "onAbilityForeground uiability:" + JSON.stringify(uiability));
},
onAbilityBackground(ability) {
console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability));
onAbilityBackground(uiability) {
console.info(TAG, "onAbilityBackground uiability:" + JSON.stringify(uiability));
},
onAbilityContinue(ability) {
console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability));
onAbilityContinue(uiability) {
console.info(TAG, "onAbilityContinue uiability:" + JSON.stringify(uiability));
}
}
// 1. 通过context属性获取applicationContext
......
......@@ -9,7 +9,7 @@ ExtensionAbility组件是基于特定场景(例如服务卡片、输入法等
- [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md):FORM类型的ExtensionAbility组件,用于提供服务卡片场景相关能力。
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md):WORK_SCHEDULER类型的ExtensionAbility组件,用于提供延迟任务注册、取消、查询的能力。
- [WorkSchedulerExtensionAbility](../reference/apis/js-apis-resourceschedule-workScheduler.md):WORK_SCHEDULER类型的ExtensionAbility组件,用于提供延迟任务回调实现的能力。
- [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md):INPUT_METHOD类型的ExtensionAbility组件,提供对输入法框架的管理,包括隐藏输入法、查询已安装的输入法列表和显示输入法选择对话框。
......
......@@ -9,7 +9,7 @@
| 任务 | 简介 | 相关指导 |
| -------- | -------- | -------- |
| 应用组件开发 | 本章节介绍了如何使用FA模型的PageAbility、ServiceAbility、DataAbility以及服务卡片进行应用开发。 | [应用/组件级配置](application-component-configuration-fa.md)<br/>[PageAbility开发指导](pageability-overview.md)<br/>[ServiceAbility开发指导](serviceability-overview.md)<br/>[DataAbility开发指导](dataability-overview.md)<br/>[服务卡片开发指导](widget-development-fa.md)<br/>[FA模型的Context](application-context-fa.md)<br/>[信息传递载体Want](want-fa.md) |
| 进程间通信 | 本章节介绍了FA模型的进程模型以及几种常用的进程间通信方式。 | [公共事件](common-event-fa.md)<br/>[RPC通信](rpc.md) |
| 进程间通信 | 本章节介绍了FA模型的进程模型以及几种常用的进程间通信方式。 | [公共事件](common-event-fa.md)<br/>[后台服务](rpc.md) |
| 线程间通信 | 本章节介绍了FA模型的线程模型以及几种常用的线程间通信方式。 | [线程间通信](itc-fa-overview.md) |
| 任务管理 | 本章节介绍了FA模型中任务管理的基本概念和典型场景。 | [任务管理](mission-management-fa.md) |
| 应用配置文件 | 本章节介绍FA模型中应用配置文件的开发要求。 | [FA模型应用配置文件](config-file-fa.md) |
......@@ -21,7 +21,7 @@
- [Context](application-context-stage.md)
在Stage模型上,Context及其派生类向开发者提供在运行期可以调用的各种能力。UIAbility组件和各种ExtensionAbility派生类都有各自不同的Context类,他们都继承自基类Context,但是各自又根据所属组件,提供不同的能力。
在Stage模型上,Context及其派生类向开发者提供在运行期可以调用的各种资源和能力。UIAbility组件和各种ExtensionAbility派生类都有各自不同的Context类,他们都继承自基类Context,但是各自又根据所属组件,提供不同的能力。
- [AbilityStage](abilitystage.md)
......
......@@ -4,7 +4,7 @@
启动远程PageAbility同样通过featureAbility中的startAbility接口实现。
除引入'\@ohos.ability.featureAbility'外,还需引入'\@ohos.distributedHardware.deviceManager',通过DeviceManager(该组件在OpenHarmony上提供号无关的分布式设备的认证组网能力)的getTrustedDeviceListSync接口(获取信任设备列表)获取远端的deviceId,写入want中,用于启动远程PageAbility。
除引入'\@ohos.ability.featureAbility'外,还需引入'\@ohos.distributedHardware.deviceManager',通过DeviceManager(该组件在OpenHarmony上提供号无关的分布式设备的认证组网能力)的getTrustedDeviceListSync接口(获取信任设备列表)获取远端的deviceId,写入want中,用于启动远程PageAbility。
由于当前DeviceManager的getTrustedDeviceListSync接口仅对系统应用开放,故现阶段非系统应用无法获取其他设备信息,无远程启动设备选择入口,远程启动Ability开发。
......
......@@ -8,7 +8,7 @@ OpenHarmony相机模块支持相机业务的开发,开发者可以通过已开
- **相机静态能力**:用于描述相机的固有能力的一系列参数,比如朝向、支持的分辨率等信息。
- **物理相机**:物理相机就是独立的实体摄像头设备。物理相机ID是用于标志每个物理摄像头的唯一字串。
- **异步操作**:为保证UI线程不被阻塞,大部分Camera调用都是异步的。对于每个API均提供了callback函数和Promise函数。
- **异步操作**:为保证UI线程不被阻塞,部分Camera接口采用异步调用方式。异步方式API均提供了callback函数和Promise函数。
## 开发步骤
......@@ -60,73 +60,99 @@ import media from '@ohos.multimedia.media'
// 创建CameraManager对象
context: any = getContext(this)
let cameraManager = await camera.getCameraManager(this.context)
let cameraManager = camera.getCameraManager(this.context)
if (!cameraManager) {
console.error('Failed to get the CameraManager instance');
}
console.error("camera.getCameraManager error")
return;
}
// 监听相机状态变化
cameraManager.on('cameraStatus', (cameraStatusInfo) => {
console.log(`camera : ${cameraStatusInfo.camera.cameraId}`);
console.log(`status: ${cameraStatusInfo.status}`);
})
// 获取相机列表
let cameraArray = await cameraManager.getSupportedCameras()
if (!cameraArray) {
console.error('Failed to get the cameras');
}
let cameraArray = cameraManager.getSupportedCameras();
if (cameraArray.length <= 0) {
console.error("cameraManager.getSupportedCameras error")
return;
}
for (let index = 0; index < cameraArray.length; index++) {
console.log('cameraId : ' + cameraArray[index].cameraId) // 获取相机ID
console.log('cameraPosition : ' + cameraArray[index].cameraPosition) // 获取相机位置
console.log('cameraType : ' + cameraArray[index].cameraType) // 获取相机类型
console.log('connectionType : ' + cameraArray[index].connectionType) // 获取相机连接类型
console.log('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID
console.log('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置
console.log('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型
console.log('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型
}
// 创建相机输入流
let cameraInput = await cameraManager.createCameraInput(cameraArray[0])
let cameraInput
try {
cameraInput = cameraManager.createCameraInput(cameraArray[0]);
} catch () {
console.error('Failed to createCameraInput errorCode = ' + error.code);
}
// 监听cameraInput错误信息
let cameraDevice = cameraArray[0];
cameraInput.on('error', cameraDevice, (error) => {
console.log(`Camera input error code: ${error.code}`);
})
// 打开相机
await cameraInput.open();
// 获取相机设备支持的输出流能力
let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]);
let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]);
if (!cameraOutputCap) {
console.error("outputCapability outputCapability == null || undefined")
} else {
console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
console.error("cameraManager.getSupportedOutputCapability error")
return;
}
console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
let previewProfilesArray = cameraOutputCap.GetPreviewProfiles();
let previewProfilesArray = cameraOutputCap.previewProfiles;
if (!previewProfilesArray) {
console.error("createOutput previewProfilesArray == null || undefined")
}
let photoProfilesArray = cameraOutputCap.GetPhotoProfiles();
let photoProfilesArray = cameraOutputCap.photoProfiles;
if (!photoProfilesArray) {
console.error("createOutput photoProfilesArray == null || undefined")
}
let videoProfilesArray = cameraOutputCap.GetVideoProfiles();
let videoProfilesArray = cameraOutputCap.videoProfiles;
if (!videoProfilesArray) {
console.error("createOutput videoProfilesArray == null || undefined")
}
let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType();
let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes;
if (!metadataObjectTypesArray) {
console.error("createOutput metadataObjectTypesArray == null || undefined")
}
// 创建预览输出流,其中参数 surfaceId 参考下面 XComponent 组件,预览流为XComponent组件提供的surface
let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
if (!previewOutput) {
let previewOutput
try {
previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
} catch (error) {
console.error("Failed to create the PreviewOutput instance.")
}
// 监听预览输出错误信息
previewOutput.on('error', (error) => {
console.log(`Preview output error code: ${error.code}`);
})
// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置
let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
// 获取照片显示SurfaceId
let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
// 创建拍照输出流
let photoOutput = await cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
if (!photoOutput) {
console.error('Failed to create the PhotoOutput instance.');
return;
let photoOutput
try {
photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
} catch (error) {
console.error('Failed to createPhotoOutput errorCode = ' + error.code);
}
// 创建视频录制的参数
......@@ -169,11 +195,17 @@ videoRecorder.getInputSurface().then((id) => {
})
// 创建VideoOutput对象
let videoOutput = await cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
if (!videoOutput) {
console.error('Failed to create the videoOutput instance.');
return;
let videoOutput
try {
videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
} catch (error) {
console.error('Failed to create the videoOutput instance. errorCode = ' + error.code);
}
// 监听视频输出错误信息
videoOutput.on('error', (error) => {
console.log(`Preview output error code: ${error.code}`);
})
```
预览流、拍照流和录像流的输入均需要提前创建surface,其中预览流为XComponent组件提供的surface,拍照流为ImageReceiver提供的surface,录像流为VideoRecorder的surface。
......@@ -247,24 +279,45 @@ function getVideoRecorderSurface() {
```typescript
//创建会话
let captureSession = await camera.createCaptureSession()
if (!captureSession) {
console.error('Failed to create the CaptureSession instance.');
return;
let captureSession
try {
captureSession = cameraManager.createCaptureSession()
} catch (error) {
console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code);
}
console.log('Callback returned with the CaptureSession instance.' + session);
// 监听session错误信息
captureSession.on('error', (error) => {
console.log(`Capture session error code: ${error.code}`);
})
// 开始配置会话
await captureSession.beginConfig()
try {
captureSession.beginConfig()
} catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code);
}
// 向会话中添加相机输入流
await captureSession.addInput(cameraInput)
try {
captureSession.addInput(cameraInput)
} catch (error) {
console.error('Failed to addInput. errorCode = ' + error.code);
}
// 向会话中添加预览输入流
await captureSession.addOutput(previewOutput)
try {
captureSession.addOutput(previewOutput)
} catch (error) {
console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code);
}
// 向会话中添加拍照输出流
await captureSession.addOutput(photoOutput)
try {
captureSession.addOutput(photoOutput)
} catch (error) {
console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code);
}
// 提交会话配置
await captureSession.commitConfig()
......@@ -282,13 +335,25 @@ await captureSession.start().then(() => {
await captureSession.stop()
// 开始配置会话
await captureSession.beginConfig()
try {
captureSession.beginConfig()
} catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code);
}
// 从会话中移除拍照输出流
await captureSession.removeOutput(photoOutput)
try {
captureSession.removeOutput(photoOutput)
} catch (error) {
console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code);
}
// 向会话中添加录像输出流
await captureSession.addOutput(videoOutput)
try {
captureSession.addOutput(videoOutput)
} catch (error) {
console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code);
}
// 提交会话配置
await captureSession.commitConfig()
......@@ -303,71 +368,65 @@ await captureSession.start().then(() => {
```typescript
// 判断设备是否支持闪光灯
let flashStatus = await captureSession.hasFlash()
if (!flashStatus) {
console.error('Failed to check whether the device has the flash mode.');
let flashStatus
try {
flashStatus = captureSession.hasFlash()
} catch (error) {
console.error('Failed to hasFlash. errorCode = ' + error.code);
}
console.log('Promise returned with the flash light support status:' + flashStatus);
if (flashStatus) {
// 判断是否支持自动闪光灯模式
let flashModeStatus
captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => {
if (err) {
console.error('Failed to check whether the flash mode is supported. ${err.message}');
return;
}
console.log('Callback returned with the flash mode support status: ' + status);
try {
let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO)
flashModeStatus = status
})
} catch (error) {
console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code);
}
if(flashModeStatus) {
// 设置自动闪光灯模式
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => {
if (err) {
console.error('Failed to set the flash mode ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setFlashMode.');
})
try {
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO)
} catch (error) {
console.error('Failed to set the flash mode. errorCode = ' + error.code);
}
}
}
// 判断是否支持连续自动变焦模式
let focusModeStatus
captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => {
if (err) {
console.error('Failed to check whether the focus mode is supported. ${err.message}');
return;
}
console.log('Callback returned with the focus mode support status: ' + status);
try {
let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
focusModeStatus = status
})
} catch (error) {
console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code);
}
if (focusModeStatus) {
// 设置连续自动变焦模式
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => {
if (err) {
console.error('Failed to set the focus mode ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setFocusMode.');
})
try {
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
} catch (error) {
console.error('Failed to set the focus mode. errorCode = ' + error.code);
}
}
// 获取相机支持的可变焦距比范围
let zoomRatioRange = await captureSession.getZoomRatioRange()
if (!zoomRatioRange) {
console.error('Failed to get the zoom ratio range.');
return;
let zoomRatioRange
try {
zoomRatioRange = captureSession.getZoomRatioRange()
} catch (error) {
console.error('Failed to get the zoom ratio range. errorCode = ' + error.code);
}
// 设置可变焦距比
captureSession.setZoomRatio(zoomRatioRange[0], async (err) => {
if (err) {
console.error('Failed to set the zoom ratio value ${err.message}');
return;
}
console.log('Callback returned with the successful execution of setZoomRatio.');
})
try {
captureSession.setZoomRatio(zoomRatioRange[0])
} catch (error) {
console.error('Failed to set the zoom ratio value. errorCode = ' + error.code);
}
```
#### 拍照
......@@ -428,7 +487,7 @@ videoOutput.stop((err) => {
captureSession.stop()
// 释放相机输入流
cameraInput.release()
cameraInput.close()
// 释放预览输出流
previewOutput.release()
......@@ -449,4 +508,4 @@ captureSession = null
## 流程图
应用使用相机的流程示意图如下
![camera_framework process](figures/camera_framework_process.jpg)
\ No newline at end of file
![camera_framework process](figures/camera_framework_process.png)
\ No newline at end of file
......@@ -46,33 +46,77 @@ struct bindPopupPage {
## 状态变量数据类型声明使用限制
@State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。
示例:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
//错误写法: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
1. 所有的状态装饰器变量需要显式声明变量类型,不允许声明any,不支持Date数据类型。
示例:
```ts
// xxx.ets
@Entry
@Component
struct DatePickerExample {
//错误写法: @State isLunar: any = false
@State isLunar: boolean = false
//错误写法: @State selectedDate: Date = new Date('2021-08-08')
private selectedDate: Date = new Date('2021-08-08')
build() {
Column() {
Button('切换公历农历')
.margin({ top: 30 })
.onClick(() => {
this.isLunar = !this.isLunar
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
.lunar(this.isLunar)
.onChange((value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info('select current date is: ' + JSON.stringify(value))
})
}.width('100%')
}
.width('100%')
}
.height('100%')
}
}
```
```
![datePicker](../../application-dev/reference/arkui-ts/figures/datePicker.gif)
2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。
类型定义中的Length、Resource、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。
Length、Resource、ResourceColor的定义请看文档[arkui-ts类型定义](../../application-dev/reference/arkui-ts/ts-types.md)。
示例:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
//错误写法: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
//错误写法: @State message: ResourceStr = $r('app.string.hello')
@State resourceStr: Resource = $r('app.string.hello')
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
![hello](figures/hello.PNG)
![hello](figures/hello.PNG)
## 自定义组件成员变量初始化的方式与约束
......@@ -98,6 +142,8 @@ struct IndexPage {
| @Link | 禁止 | 必须 |
| @StorageLink | 必须 | 禁止 |
| @StorageProp | 必须 | 禁止 |
| @LocalStorageLink | 必须 | 禁止 |
| @LocalStorageProp | 必须 | 禁止 |
| @Provide | 必须 | 可选 |
| @Consume | 禁止 | 禁止 |
| @ObjectLink | 禁止 | 必须 |
......@@ -111,25 +157,77 @@ struct IndexPage {
通过构造函数方法初始化成员变量,需要遵循如下规则:
| 从父组件中的变量(下)到子组件中的变量(右) | @State | @Link | @Prop | 常规变量 |
| -------------------------------------------- | ------ | ------ | ------ | -------- |
| @State | 不允许 | 允许 | 允许 | 允许 |
| @Link | 不允许 | 允许 | 不推荐 | 允许 |
| @Prop | 不允许 | 不允许 | 允许 | 允许 |
| @StorageLink | 不允许 | 允许 | 不允许 | 不允许 |
| @StorageProp | 不允许 | 不允许 | 不允许 | 允许 |
| 常规变量 | 允许 | 不允许 | 不允许 | 允许 |
| **从父组件中的变量(右)到子组件中的变量(下)** | **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
| **regular** | 支持 | 支持 | 支持 | 支持 | 不支持 | 不支持 | 支持 |
| **@State** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **@Link** | 不支持 | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) |
| **@Prop** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **@Provide** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 |
| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 |
| **从父组件中的变量(右)到子组件中的变量(下)** | **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** |
|------------------|------------------|------------------|-----------------------|------------------------|
| **regular** | 支持 | 不支持 | 不支持 | 不支持 |
| **@State** | 支持 | 支持 | 支持 | 支持 |
| **@Link** | 支持(1) | 支持(1) | 支持(1) | 支持(1) |
| **@Prop** | 支持 | 支持 | 支持 | 支持 |
| **@Provide** | 支持 | 支持 | 支持 | 支持 |
| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 |
| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 |
> **说明**
>
> **支持(1)**:必须使用`$`, 例如 `this.$varA`。
> **regular**:未加修饰的常规变量。
从上表中可以看出:
- 父组件的常规变量可以用于初始化子组件的@State变量,但不能用于初始化@Link或@Prop变量。
- 子组件的@ObjectLink变量不支持父组件装饰器变量的直接赋值,其父组件的源必须是数组的项或对象的属性,该数组或对象必现用`@State``@Link``@Provide``@Consume``@ObjectLink`装饰器修饰。
- 父组件的常规变量可以用于初始化子组件的`@State`变量,但不能用于初始化`@Link``@Consume``@ObjectLink`变量。
- 父组件的@State变量可以初始化子组件的@Prop、@Link(通过$)或常规变量,但不能初始化子组件的@State变量。
- 父组件的@State变量可以初始化子组件的`@Prop``@Link`(通过$)或常规变量,但不能初始化子组件的@Consume变量。
- 父组件的@Link变量可以初始化子组件的@Link或常规变量。但是初始化子组件的@State成员是语法错误,此外不建议初始化@Prop
- 父组件的@Link变量不可以初始化子组件的`@Consume``@ObjectLink`变量
- 父组件的@Prop变量可以初始化子组件的常规变量或@Prop变量,但不能初始化子组件的@State或@Link变量。
- 父组件的@Prop变量不可以初始化子组件的`@Consume``@ObjectLink`变量。
- @StorageLink和@StorageProp不允许由父组件中传递到子组件
- 不允许从父组件初始化`@StorageLink`, `@StorageProp`, `@LocalStorageLink`, `@LocalStorageProp`修饰的变量
- 除了上述规则外,还需要遵循TS的强类型规则。
\ No newline at end of file
- 除了上述规则外,还需要遵循TS的强类型规则。
示例:
```ts
@Entry
@Component
struct Parent {
message: string = "Hello World"
build() {
Column() {
Child({
stateMessage: this.message,
/* ArkTS:ERROR The regular property 'message' cannot be assigned
to the @Link property 'linkMessage'.*/
linkMessage: this.$message
})
}
.width('100%')
}
}
@Component
struct Child {
@State stateMessage: string = "Hello World"
@Link linkMessage: string
build() {
Column() {
Text(this.stateMessage)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
}
```
......@@ -30,3 +30,5 @@ AppStorage是整个应用程序状态的中心“数据库”,UI框架会针
- @LocalStorageProp:组件通过使用@LocalStorageProp(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立单向数据绑定。
- PersistentStorage提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。
- Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态数据,这些数据描述了应用程序运行的设备环境。
请参考[状态变量数据类型声明的使用限制](arkts-restrictions-and-extensions.md)了解状态变量使用规范。
......@@ -261,22 +261,22 @@
- 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN
(预留事件,暂未支持)表示分布式号登录成功的动作。
(预留事件,暂未支持)表示分布式号登录成功的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGIN
- 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT
(预留事件,暂未支持)表示分布式号登出成功的动作。
(预留事件,暂未支持)表示分布式号登出成功的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOUT
- 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID
(预留事件,暂未支持)表示分布式号token令牌无效的动作。
(预留事件,暂未支持)表示分布式号token令牌无效的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID
- 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF
(预留事件,暂未支持)表示分布式号注销的动作。
(预留事件,暂未支持)表示分布式号注销的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOFF
- 订阅者所需权限: 无
......
......@@ -239,7 +239,7 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions,
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ----------------------- |
| owner | string | 是 | 应用帐号所有者的包名。 |
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 |
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 |
| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,返回创建结果。 |
**错误码:**
......@@ -2802,7 +2802,7 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;)
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当创建成功时,err为null,否则为错误对象。 |
**示例:**
......@@ -2830,7 +2830,7 @@ addAccount(name: string, extraInfo?: string): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ---------------------------------------- |
| name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 否 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| extraInfo | string | 否 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
**返回值:**
......@@ -3239,7 +3239,7 @@ setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback&lt;
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------- | ---- | --------------- |
| name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当设置成功时,err为null,否则为错误对象。 |
**示例:**
......@@ -3269,7 +3269,7 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | --------- |
| name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
**返回值:**
......@@ -4558,7 +4558,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
## CreateAccountOptions<sup>9+</sup>
表示创建号的选项。
表示创建号的选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。
......@@ -4568,7 +4568,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
## CreateAccountImplicitlyOptions<sup>9+</sup>
表示隐式创建号的选项。
表示隐式创建号的选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。
......@@ -4878,7 +4878,7 @@ createAccountImplicitly(options: CreateAccountImplicitlyOptions, callback: AuthC
| 参数名 | 类型 | 必填 | 说明 |
| ---------------- | --------------------- | ---- | --------------- |
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 |
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 |
| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,用于返回创建结果。 |
### addAccountImplicitly<sup>(deprecated)</sup>
......
......@@ -121,7 +121,7 @@ createDeviceManager(bundleName: string, callback: AsyncCallback&lt;DeviceManager
| mode | [DiscoverMode ](#discovermode) | 否 | 发现模式。 |
| medium | [ExchangeMedium](#exchangemedium) | 否 | 发现类型。 |
| freq | [ExchangeFreq](#exchangefreq) | 否 | 发现频率。 |
| isSameAccount | boolean | 否 | 是否同号。 |
| isSameAccount | boolean | 否 | 是否同号。 |
| isWakeRemote | boolean | 否 | 是否唤醒设备。 |
| capability | [SubscribeCap](#subscribecap) | 否 | 发现能力。 |
......@@ -711,7 +711,7 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async
deviceType: 0x0E
};
let authParam = {
"authType": 1, // 认证类型: 1 - 无号PIN码认证
"authType": 1, // 认证类型: 1 - 无号PIN码认证
"extraInfo": {}
}
try {
......
......@@ -755,7 +755,7 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void
| -------- | -------- | -------- | -------- |
| filename | string | 是 | multipart提交时,请求头中的文件名。 |
| name | string | 是 | multipart提交时,表单项目的名称,缺省为file。 |
| uri | string | 是 | 文件的本地存储路径。<br/>支持“dataability”和“internal”两种协议类型,但“internal”仅支持临时目录,示例:<br/>dataability:///com.domainname.dataability.persondata/person/10/file.txt<br/>internal://cache/path/to/file.txt |
| uri | string | 是 | 文件的本地存储路径。<br/>仅支持“internal”协议类型,“internal://cache/”为必填字段,示例:<br/>internal://cache/path/to/file.txt |
| type | string | 是 | 文件的内容类型,默认根据文件名或路径的后缀获取。 |
......
......@@ -66,8 +66,8 @@ requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): DelaySuspen
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspension delay will time out.");
})
var id = delayInfo.requestId;
var time = delayInfo.actualDelayTime;
let id = delayInfo.requestId;
let time = delayInfo.actualDelayTime;
console.info("The requestId is: " + id);
console.info("The actualDelayTime is: " + time);
} catch (error) {
......@@ -281,14 +281,18 @@ export default class EntryAbility extends UIAbility {
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
};
```
......@@ -352,18 +356,22 @@ export default class EntryAbility extends UIAbility {
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((error) => {
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((error) => {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
};
```
......
......@@ -89,11 +89,11 @@ upload(options: UploadRequestOptions): void
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。
| 名称 | 类型 | 说明 |
| -------- | -------- | -------- |
| code | number | 服务器返回的HTTP状态码。 |
| data | string | 服务器返回的内容。根据返回头内容中的type决定该值的类型。 |
| headers | Object | 服务器返回的返回头内容。 |
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| code | number | 是 | 服务器返回的HTTP状态码。 |
| data | string | 是 | 服务器返回的内容。根据返回头内容中的type决定该值的类型。 |
| headers | Object | 是 | 服务器返回的返回头内容。 |
## RequestFile
......@@ -189,9 +189,9 @@ download(options: DownloadRequestOptions): void
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。
| 名称 | 类型 | 说明 |
| -------- | -------- | -------- |
| token | string | 表示下载的token,获取下载状态的依据。 |
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| token | string | 是 | 表示下载的token,获取下载状态的依据。 |
## request.onDownloadComplete
......@@ -254,6 +254,6 @@ onDownloadComplete(options: OnDownloadCompleteOptions): void
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。
| 名称 | 类型 | 说明 |
| -------- | -------- | -------- |
| uri | string | 表示下载文件的uri。 |
\ No newline at end of file
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| uri | string | 是 | 表示下载文件的uri。 |
\ No newline at end of file
......@@ -1864,7 +1864,7 @@ getWindowAvoidArea(type: AvoidAreaType): AvoidArea
| 参数名 | 类型 | 必填 | 说明 |
| ---- |----------------------------------| -- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype7) | 是 | 表示规避区类型。type为TYPE_SYSTEM,表示系统默认区域。type为TYPE_CUTOUT,表示刘海屏区域。type为TYPE_SYSTEM_GESTURE,表示手势区域。type为TYPE_KEYBOARD,表示软键盘区域。 |
| type | [AvoidAreaType](#avoidareatype7) | 是 | 表示规避区类型。 |
**返回值:**
......@@ -2500,7 +2500,7 @@ off(type: 'windowSizeChange', callback?: Callback&lt;Size&gt;): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------- | ---- | -------------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'windowSizeChange',即窗口尺寸变化事件。 |
| callback | Callback&lt;[Size](#size)&gt; | 否 | 回调函数。返回当前的窗口尺寸。 |
| callback | Callback&lt;[Size](#size7)&gt; | 否 | 回调函数。返回当前的窗口尺寸。 |
**示例:**
......@@ -3006,7 +3006,7 @@ setWindowColorSpace(colorSpace:ColorSpace, callback: AsyncCallback&lt;void&gt;):
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------- | -- | ----------- |
| colorSpace | [ColorSpace](#colorspace) | 是 | 设置色域模式。 |
| colorSpace | [ColorSpace](#colorspace8) | 是 | 设置色域模式。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**错误码:**
......@@ -3045,7 +3045,7 @@ setWindowColorSpace(colorSpace:ColorSpace): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------- | -- | ------------- |
| colorSpace | [ColorSpace](#colorspace) | 是 | 设置色域模式。 |
| colorSpace | [ColorSpace](#colorspace8) | 是 | 设置色域模式。 |
**返回值:**
......@@ -3088,7 +3088,7 @@ getWindowColorSpace(): ColorSpace
| 类型 | 说明 |
| ------------------------- | ------------- |
| [ColorSpace](#colorspace) | 当前色域模式。 |
| [ColorSpace](#colorspace8) | 当前色域模式。 |
**错误码:**
......@@ -4615,7 +4615,7 @@ getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback&lt;
| 参数名 | 类型 | 必填 | 说明 |
| -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype7) | 是 | 表示规避区类型。type为TYPE_SYSTEM,表示系统默认区域。type为TYPE_CUTOUT,表示刘海屏区域。type为TYPE_SYSTEM_GESTURE,表示手势区域。type为TYPE_KEYBOARD,表示软键盘区域。 |
| type | [AvoidAreaType](#avoidareatype7) | 是 | 表示规避区类型。|
| callback | AsyncCallback&lt;[AvoidArea](#avoidarea7)&gt; | 是 | 回调函数。返回窗口内容规避区域。 |
**示例:**
......@@ -4647,7 +4647,7 @@ getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise&lt;[AvoidArea](#av
| 参数名 | 类型 | 必填 | 说明 |
| ------ |----------------------------------| ---- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype7) | 是 | 表示规避区类型。type为TYPE_SYSTEM,表示系统默认区域。type为TYPE_CUTOUT,表示刘海屏区域。type为TYPE_SYSTEM_GESTURE,表示手势区域。type为TYPE_KEYBOARD,表示软键盘区域。 |
| type | [AvoidAreaType](#avoidareatype7) | 是 | 表示规避区类型。 |
**返回值:**
......@@ -5205,7 +5205,7 @@ setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------- | ---- | ------------ |
| colorSpace | [ColorSpace](#colorspace) | 是 | 设置色域模式。 |
| colorSpace | [ColorSpace](#colorspace8) | 是 | 设置色域模式。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:**
......@@ -5236,7 +5236,7 @@ setColorSpace(colorSpace:ColorSpace): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------- | ---- | -------------- |
| colorSpace | [ColorSpace](#colorspace) | 是 | 设置色域模式。 |
| colorSpace | [ColorSpace](#colorspace8) | 是 | 设置色域模式。 |
**返回值:**
......@@ -5271,7 +5271,7 @@ getColorSpace(callback: AsyncCallback&lt;ColorSpace&gt;): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ---------------------------------------------------------- |
| callback | AsyncCallback&lt;[ColorSpace](#colorspace)&gt; | 是 | 回调函数。当获取成功,err为undefined,data为当前色域模式。 |
| callback | AsyncCallback&lt;[ColorSpace](#colorspace8)&gt; | 是 | 回调函数。当获取成功,err为undefined,data为当前色域模式。 |
**示例:**
......@@ -5301,7 +5301,7 @@ getColorSpace(): Promise&lt;ColorSpace&gt;
| 类型 | 说明 |
| ---------------------------------------- | ------------------------------- |
| Promise&lt;[ColorSpace](#colorspace)&gt; | Promise对象。返回当前色域模式。 |
| Promise&lt;[ColorSpace](#colorspace8)&gt; | Promise对象。返回当前色域模式。 |
**示例:**
......
......@@ -3261,7 +3261,7 @@ confirm(userName: string, pwd: string): boolean
isHttpAuthInfoSaved(): boolean
通知Web组件用户使用服务器缓存的号密码认证。
通知Web组件用户使用服务器缓存的号密码认证。
**返回值:**
......
......@@ -200,7 +200,7 @@ focusControl.requestFocus示例代码:
使用focusContrl.requestFocus接口使指定组件获取焦点。
```ts
// requestFocus.ets
import prompt from '@ohos.prompt'
import promptAction from '@ohos.promptAction';
@Entry
@Component
......@@ -252,9 +252,9 @@ struct RequestFocusExample {
.onClick(() => {
var res = focusControl.requestFocus(this.selectId) // 使选中的this.selectId的组件获焦
if (res) {
prompt.showToast({message: 'Request success'})
promptAction.showToast({message: 'Request success'})
} else {
prompt.showToast({message: 'Request failed'})
promptAction.showToast({message: 'Request failed'})
}
})
}
......
......@@ -989,7 +989,7 @@ TS/JS语言基础库
## SystemCapability.Account.AppAccount
应用
应用
| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
......
......@@ -246,7 +246,7 @@
## ohos.permission.MANAGE_LOCAL_ACCOUNTS
允许应用管理本地用户号。
允许应用管理本地用户号。
**权限级别**:system_basic
......@@ -256,7 +256,7 @@
## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
允许多个系统号之间相互访问。
允许多个系统号之间相互访问。
**权限级别**:system_basic
......
......@@ -100,13 +100,13 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业
- 携带参数信息支持number、string、bool三种类型。
## 申请能效资源
能效资源可以分为四种:CPU资源,WORK_SCHEDULER资源,软件资源(COMMON_EVENT,TIMER),硬件资源(GPS,BLUETOOTH,AUDIO)。
供系统应用使用的能效资源可以分为两类:软件资源(WORK_SCHEDULER, COMMON_EVENT, TIMER),硬件资源(CPU, GPS, BLUETOOTH, AUDIO)。
应用或进程申请能效资源后能够获得相应特权
应用申请不同的能效资源后可以执行相应的操作
* 申请CPU资源后可以不被挂起,直到任务完成。
* 申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加
* 申请COMMON_EVENT资源后,应用在后台处于挂起状态时,仍然能够接收到系统公共事件,申请TIMER资源后,应用能够使用定时器执行精确定时任务
* 申请硬件资源后,应用在后台被挂起后,依然能够被相关服务唤醒,执行相应的任务。
* 申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加
* 申请COMMON_EVENT资源后,应用在后台处于挂起状态时,仍然能够接收到系统公共事件,申请TIMER资源后,应用能够使用定时器执行精确定时任务
* 申请资源(GPS, BLUETOOTH, AUDIO)后,应用在后台被挂起后,依然能够被管理相关硬件的服务唤醒,执行相应的任务。
**表1** 能效资源种类
......@@ -125,4 +125,4 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业
- 能效资源申请或者释放可以由进程或者应用发起,由应用发起的资源释放会释放属于它的同类型的所有资源,包括进程申请的资源。例如应用申请了CPU资源,进程申请了CPU和WORK_SCHEDULER资源,当应用释放CPU资源的时候,会将进程的CPU资源一同释放,同时不同类型的WORK_SCHEDULER资源不受影响。由进程发起的资源释放对应用申请的资源没有影响,例如当应用和进程同时申请了CPU,进程发起了CPU资源释放,应用的CPU资源不会被释放。
- 同时申请同一类持久资源和非持久资源,持久资源会覆盖非持久资源,在超时时不会释放资源。例如应用首先申请了10s的CPU资源,然后在第5s的时候申请了持久的CPU资源,那么资源会变成持久的,非持久的CPU资源记录会被持久化的CPU资源记录覆盖,到了第10s的时候资源不会被释放,如果在第8s的时候提前释放了资源,那么会将CPU资源释放,无法单独释放其中非持久的或者持久的CPU资源。
- WORK_SCHEDULER资源只能由应用申请和释放,不能由进程申请和释放。
- 需要使用能效资源的应用,需要向应用中心提出申请,获取相应的特权。
- 需要使用能效资源的应用必须是系统应用,同时需要向应用中心提出申请,配置相应的特权。
......@@ -89,18 +89,22 @@ struct Index {
};
// 通过wantAgent模块的getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
stopContinuousTask() {
......@@ -151,7 +155,7 @@ struct Index {
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.app.ability.wantAgent';
const MSG_SEND_METHOD: string = 'CallSendMsg';
......@@ -176,25 +180,29 @@ function startContinuousTask() {
};
// 通过wantAgent模块的getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((error) => {
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(mContext,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((error) => {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
}).catch((error) => {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
......@@ -312,7 +320,7 @@ export default class BgTaskAbility extends UIAbility {
2、在Service Ability调用长时任务的申请和取消接口。
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
......@@ -335,18 +343,22 @@ function startContinuousTask() {
};
// 通过wantAgent模块的getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
function stopContinuousTask() {
......@@ -396,7 +408,7 @@ class MyStub extends rpc.RemoteObject {
}
export default {
onStart(want) {
onStart() {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
// 在执行后台长时任前,调用申请接口。
......@@ -416,7 +428,7 @@ export default {
onDisconnect() {
console.info('ServiceAbility onDisconnect');
},
onCommand(want, restart, startId) {
onCommand(want, startId) {
console.info('ServiceAbility onCommand');
}
};
......
......@@ -23,7 +23,7 @@
2、当资源使用完毕,需要及时释放。支持释放部分资源或全部资源。
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
// 申请能效资源
let request = {
......@@ -35,8 +35,14 @@ let request = {
isPersist: true,
isProcess: true,
};
let res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
let res;
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
// 释放部分资源
request = {
......@@ -44,10 +50,20 @@ request = {
isApply: false,
timeOut: 0,
reason: "reset",
isPersist: true,
isProcess: true,
};
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
// 释放全部资源
backgroundTaskManager.resetAllEfficiencyResources();
try {
backgroundTaskManager.resetAllEfficiencyResources();
} catch (error) {
console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
```
......@@ -43,7 +43,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
导入模块。
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
实现WorkSchedulerExtension生命周期接口。
......@@ -52,27 +52,27 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
export default class workAbility extends WorkSchedulerExtensionAbility {
// 延迟任务开始回调
onWorkStart(workInfo) {
console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`)
console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`);
// 发送升级通知
let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, '')
let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, '');
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`)
console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`);
}
console.log(`onWorkStart notification publish success`)
})
console.log(`onWorkStart notification publish success`);
});
}
// 延迟任务结束回调
onWorkStop(workInfo) {
// 发送升级完成通知
let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '')
let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '');
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`)
console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`);
}
console.log(`onWorkStop notification publish success`)
})
console.log(`onWorkStop notification publish success`);
});
}
}
```
......@@ -91,13 +91,13 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
```ts
export default class WorkTest extends workAbility {
onWorkStart(workInfo) {
console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`)
super.onWorkStart(workInfo)
console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`);
super.onWorkStart(workInfo);
}
onWorkStopTest(workInfo) {
super.onWorkStop(workInfo)
console.log(`onWorkStop value`)
super.onWorkStop(workInfo);
console.log(`onWorkStop value`);
}
}
```
......@@ -109,7 +109,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
导入模块。
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler'
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
封装延迟任务注册、停止接口。
......@@ -124,25 +124,25 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
}
// 注册延迟任务
startWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName
this.workInfo.abilityName = abilityName
this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName;
try {
workScheduler.startWork(this.workInfo)
console.log(`startWork success`)
workScheduler.startWork(this.workInfo);
console.log(`startWork success`);
} catch (error) {
Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`)
Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`);
prompt.showToast({
message: `${error.message}`
})
});
}
}
// 停止延迟任务
stopWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName
this.workInfo.abilityName = abilityName
workScheduler.stopWork(this.workInfo, false)
console.log(`stopWork`)
this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName;
workScheduler.stopWork(this.workInfo, false);
console.log(`stopWork`);
}
}
```
......@@ -152,7 +152,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
导入模块。
```ts
import { workAbility } from '@ohos/library'
import { workAbility } from '@ohos/library';
```
增加“升级”按钮,调用library封装的延迟任务注册接口,传入bundleName和abilityName,其中bilityName为WorkTest。
......@@ -163,15 +163,15 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
.height(40)
.fontSize(30)
.onClick(() => {
this.work.startWork('ohos.samples.workscheduler', 'WorkTest')
})
this.work.startWork('ohos.samples.workscheduler', 'WorkTest');
});
```
在组件析构时,调用延迟任务停止接口。
```ts
aboutToDisappear() {
this.work.stopWork('ohos.samples.workscheduler', 'WorkTest')
this.work.stopWork('ohos.samples.workscheduler', 'WorkTest');
}
```
......
......@@ -49,30 +49,30 @@
- 可以通过`window.createWindow`接口创建子窗口。
- 也可以通过`window.findWindow`接口来查找已经创建的窗口从而得到子窗口。
```js
import window from '@ohos.window';
```js
import window from '@ohos.window';
let windowClass = null;
// 方式一:创建子窗口。
let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP};
window.createWindow(config, (err, data) => {
if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
// 方式二:查找得到子窗口。
window.findWindow("subWindow", (err, data) => {
if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
```
let windowClass = null;
// 方式一:创建子窗口。
let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP};
window.createWindow(config, (err, data) => {
if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
// 方式二:查找得到子窗口。
window.findWindow("subWindow", (err, data) => {
if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data));
windowClass = data;
});
```
2. 设置子窗口属性。
......
# 公共基础库常见问题
## LiteOS-A内核(Hi3516、Hi3518平台)KV存储路径设置错误,导致KV存储运行失败
**现象描述**
LiteOS-A内核(Hi3516、Hi3518平台)直接调用KV存储提供的接口,各参数正常的情况下,编译可执行程序运行失败。
**可能原因**
直接运行编译出的可执行文件,没有将程序基于AbilityKit转换成应用,不能由BMS在应用安装时正确设置应用数据存储路径,导致KV存储运行失败。
**解决办法**
显示调用KV存储的UtilsSetEnv接口,设置数据存储路径。
```
UtilsSetEnv("/storage/com.example.kv");
```
# 公共基础库开发指导
## 接口说明
**表1** 文件操作接口说明
| 接口名 | 描述 |
| -------- | -------- |
| int&nbsp;UtilsFileOpen(const&nbsp;char\*&nbsp;path,&nbsp;int&nbsp;oflag,&nbsp;int&nbsp;mode) | 打开或创建文件 |
| int&nbsp;UtilsFileClose(int&nbsp;fd) | 关闭文件 |
| int&nbsp;UtilsFileRead(int&nbsp;fd,&nbsp;char&nbsp;\*buf,&nbsp;unsigned&nbsp;int&nbsp;len) | 读取特定长度的文件数据 |
| int&nbsp;UtilsFileWrite(int&nbsp;fd,&nbsp;const&nbsp;char&nbsp;\*buf,&nbsp;unsigned&nbsp;int&nbsp;len) | 向文件写入特定大小的数据 |
| int&nbsp;UtilsFileDelete(const&nbsp;char&nbsp;\*path) | 删除指定文件 |
| int&nbsp;UtilsFileStat(const&nbsp;char&nbsp;\*path,&nbsp;unsigned&nbsp;int&nbsp;\*fileSize) | 获取文件大小 |
| int&nbsp;UtilsFileSeek(int&nbsp;fd,&nbsp;int&nbsp;offset,&nbsp;unsigned&nbsp;int&nbsp;whence) | 重新定位文件读/写偏移量 |
| int&nbsp;UtilsFileCopy(const&nbsp;char\*&nbsp;src,&nbsp;const&nbsp;char\*&nbsp;dest) | 将源文件复制一份并存储到目标文件 |
| int&nbsp;UtilsFileMove(const&nbsp;char\*&nbsp;src,&nbsp;const&nbsp;char\*&nbsp;dest) | 将源文件移动到指定目标文件 |
文件操作使用示例:
```
// open && write
char fileName[] = "testfile";
static const char def[] = "utils_file_operation implement.";
int fd = UtilsFileOpen(fileName, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0);
printf("file handle = %d\n", fd);
int ret = UtilsFileWrite(fd, def, strlen(def));
printf("write ret = %d\n", ret);
// seek
ret = UtilsFileSeek(fd, 5, SEEK_SET_FS);
printf("lseek ret = %d\n", ret);
// read && close
char buf[64] = {0};
int readLen = UtilsFileRead(fd, buf, 64);
ret = UtilsFileClose(fd);
printf("read len = %d : buf = %s\n", readLen, buf);
// stat
int fileLen = 0;
ret = UtilsFileStat(fileName, &fileLen);
printf("file size = %d\n", fileLen);
// delete
ret = UtilsFileDelete(fileName);
printf("delete ret = %d\n", ret);
# 公共基础类库开发指导
## 概述
公共基础类库存放OpenHarmony通用的基础组件。这些基础组件包括一些常用的C、C++、JS开发增强API,可被OpenHarmony各业务子系统及上层应用所使用。公共基础类库子系统包含如下代码仓库:
```
**表2** KV存储接口说明
| 接口名 | 描述 |
| -------- | -------- |
| int&nbsp;UtilsGetValue(const&nbsp;char\*&nbsp;key,&nbsp;char\*&nbsp;value,&nbsp;unsigned&nbsp;int&nbsp;len) | 提供给上层应用根据key获取对应数据项 |
| int&nbsp;UtilsSetValue(const&nbsp;char\*&nbsp;key,&nbsp;const&nbsp;char\*&nbsp;value) | 提供给上层应用用于存储/更新key对应数据项 |
| int&nbsp;UtilsDeleteValue(const&nbsp;char\*&nbsp;key) | 提供给上层应用删除key对应数据项 |
KV存储使用示例:
```
// set
char key[] = "rw.sys.version_100";
char value[] = "Hello kv operation implement!";
int ret = UtilsSetValue(key, value);
printf("UtilsSetValue set ret = %d\n", ret);
// get
char temp[128] = {0};
ret = UtilsGetValue(key, temp, 128);
printf("UtilsGetValue get ret = %d, temp = %s\n", ret, temp);
// delete
ret = UtilsDeleteValue(key);
printf("UtilsDeleteValue delete ret = %d\n", ret);
/commonlibrary
├── c_utils # c/c++标准库之外方便开发者开发的基础工具库
├── ets_utils # js标准库之外的与语言强相关的基础库
└── utils_lite # lite上使用的工具函数,涉及c和js语言
```
各仓库提供的功能列表如下:
**c_utils**
- 文件、路径、字符串相关操作的能力增强接口;
- 读写锁、信号量、定时器、线程增强及线程池等接口;
- 安全数据容器、数据序列化等接口;
- 各子系统的错误码相关定义;
## 开发步骤
### LiteOS-A内核(Hi3516、Hi3518平台)KV存储的native应用开发:
1. 基于AbilityKit开发KV存储的native应用。
- 基于KV存储提供的接口编写用户程序,并编译出so(libLauncher.so)文件。
```
// set
char key[] = "rw.sys.version_100";
char value[] = "Hello kv operation implement!";
int ret = UtilsSetValue(key, value);
printf("UtilsSetValue set ret = %d\n", ret);
// get
char temp[128] = {0};
ret = UtilsGetValue(key, temp, 128);
printf("UtilsGetValue get ret = %d, temp = %s\n", ret, temp);
// delete
ret = UtilsDeleteValue(key);
printf("UtilsDeleteValue delete ret = %d\n", ret);
```
- 编写config.json文件,内容如下:
```
{
"app": {
"bundleName": "com.example.launcher",
"vendor": "example",
"version": {
"code": 1,
"name": "1.0"
}
},
"deviceConfig": {
"default": {
"reqSdk": {
"compatible": "zsdk 1.0.0",
"target": "zsdk 1.0.1"
},
"keepAlive": false
},
"smartCamera": {
"reqSdk": {
"compatible": "zsdk 1.0.0",
"target": "zsdk 1.0.1"
},
"keepAlive": false
}
},
"module": {
"package": "com.example.launcher",
"name": ".MyOpenHarmonyAbilityPackage",
"deviceType": [
"phone", "tv","tablet", "pc","car","smartWatch","sportsWatch","smartCamera"
],
"distro": {
"deliveryWithInstall": true,
"moduleName": "Launcher",
"moduleType": "entry"
},
"abilities": [{
"name": "MainAbility",
"icon": "res/drawable/phone.png",
"label": "test app 1",
"launchType": "standard",
"type": "page"
},
{
"name": "SecondAbility",
"icon": "res/drawable/phone.png",
"label": "test app 2",
"launchType": "standard",
"type": "page"
},
{
"name": "ServiceAbility",
"icon": "res/drawable/phone.png",
"label": "test app 2",
"launchType": "standard",
"type": "service"
}
]
}
}
```
- 生成hap包。
- 按照如下目录结构存放文件,res/drawable下面放置资源文件:
**图1** 资源文件路径图
![zh-cn_image_0000001154153558](figures/zh-cn_image_0000001154153558.png)
- 将上述文件打包生成zip包,修改后缀为.hap,例如Launcher.hap
2. 连接单板,通过串口向单板发送安装KV存储native应用的命令。
```
./nfs/dev_tools/bin/bm install -p /nfs/Launcher.hap
```
3. 通过串口向单板发送运行KV存储native应用的命令。
```
./nfs/dev_tools/bin/aa start -p com.example.launcher -n ServiceAbility
```
### Dump系统属性在LiteOS-M内核平台使用:
1. 连接单板,通过串口向单板发送AT+SYSPARA命令。
```
AT+SYSPARA
```
**图2** LiteOS-M平台dump系统属性输出
![zh-cn_image_0000001115123966](figures/zh-cn_image_0000001115123966.png)
### Dump系统属性在LiteOS-A内核平台使用:
**ets_utils**
1. 连接单板,运行bin路径下的os_dump加参数--help,查看os_dump使用指导。
```
./bin/os_dump --help
```
- JS中URI、URL、xml相关操作接口;
- JS中字符编解码接口;
- JS中进程相关操作接口;
- JS中多线程能力;
2. os_dump加参数-l,查看当前系统有哪些模块支持获取属性。
```
./bin/os_dump -l
```
**utils_lite**
3. os_dump加参数syspara,查看当前系统属性。
```
./bin/os_dump syspara
```
- 标准文件相关操作HAL接口;
- 其它一些内部功能,如定时器等。
**图3** LiteOS-A平台dump系统属性输出
## 各仓库开发指导
[C++公共基础库(c_utils)开发指导](https://gitee.com/openharmony/commonlibrary_c_utils/blob/master/docs/zh-cn/c-utils-guide.md)
![zh-cn_image_0000001197369959](figures/zh-cn_image_0000001197369959.png)
# 公共基础类库常见问题
## c_utils常见问题
具体各应用场景常见问题,参见[C++公共基础库(c_utils)开发指导](https://gitee.com/openharmony/commonlibrary_c_utils/blob/master/docs/zh-cn/c-utils-guide.md)
\ No newline at end of file
# 公共基础库概述
公共基础库存放OpenHarmony通用的基础组件。这些基础组件可被OpenHarmony各业务子系统及上层应用所使用。
公共基础库在不同平台上提供的能力:
LiteOS-M内核(Hi3861平台):KV存储、文件操作、IoT外设控制、Dump系统属性。
LiteOS-A内核(Hi3516、Hi3518平台):KV存储、定时器、数据和文件存储的JS API、Dump系统属性。
# 公共基础库<a name="ZH-CN_TOPIC_0000001092539399"></a>
- [简介](#section11660541593)
- [目录](#section17271017133915)
- [概述](#section11660541593)
- [相关文档](#section17271017133915)
- [相关仓](#section1249817110914)
## 简介<a name="section11660541593"></a>
## 概述<a name="section11660541593"></a>
公共基础类库提供了一些常用的C、C++、JS开发增强API。包括如下部分:
公共基础类库存放OpenHarmony通用的基础组件。这些基础组件包括一些常用的C、C++、JS开发增强API,可被OpenHarmony各业务子系统及上层应用所使用。公共基础类库子系统包含如下代码仓库:
```
/commonlibrary
├── c_utils # c/c++标准库之外方便开发者开发的基础工具库
├── ets_utils # js标准库之外的与语言强相关的基础库
└── utils_lite # lite上使用的工具函数,涉及c和js语言
```
各仓库提供的功能列表如下:
**c_utils**
......@@ -27,14 +34,8 @@
- 标准文件相关操作HAL接口;
- 其它一些内部功能,如定时器等。
## 目录<a name="section17271017133915"></a>
```
/commonlibrary
├── c_utils # c/c++标准库之外方便开发者开发的基础工具库
├── ets_utils # js标准库之外的与语言强相关的基础库
└── utils_lite # lite上使用的工具函数,涉及c和js语言
```
## 相关文档<a name="section17271017133915"></a>
[公共基础类库开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-utils-guide.md)
## 相关仓<a name="section1249817110914"></a>
......
......@@ -3,12 +3,12 @@
OpenHarmony3.2.10.3 相对 OpenHarmony3.2 Beta4 版本,媒体子系统 camera 部件 API 变更如下
## cl.subsystemname.1 camera 接口变更
1. camera 部件在 API9 版本全量改为 SystemAPI
2. 基于以下原因新增部分功能接口以及废弃部分接口:
基于以下原因新增部分功能接口以及废弃部分接口:
1. 提升开发者使用相机接口的便利。
2. 帮助开发者快速掌握相机开发接口,快速投入到开发当中。
3. 易于后续版本中框架功能的扩展,降低框架模块之间的耦合度。
提升开发者使用相机接口的便利。
帮助开发者快速掌握相机开发接口,快速投入到开发当中。
易于后续版本中框架功能的扩展,降低框架模块之间的耦合度。
具体参考下方变更内容,开发者需要根据以下说明对应用进行适配。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册