提交 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 ...@@ -81,16 +81,17 @@ You can set a USB device as the USB host to connect to other USB devices for dat
number: 1, number: 1,
type: 3, type: 3,
interfaceId: 0, interfaceId: 0,
} }
] ]
} }
] ]
} }
] ]
} }
] ]
*/ */
``` ```
2. Obtain the device operation permissions. 2. Obtain the device operation permissions.
......
...@@ -17,7 +17,7 @@ Reference: [Notification](../reference/apis/js-apis-notification.md#notification ...@@ -17,7 +17,7 @@ Reference: [Notification](../reference/apis/js-apis-notification.md#notification
Example: Example:
```ts ```ts
import WantAgent from '@ohos.wantAgent'; import WantAgent from '@ohos.app.ability.wantAgent';
async function publishNotification() { async function publishNotification() {
let wantAgentInfo = { let wantAgentInfo = {
......
# @ohos.systemTime # @ohos.systemTime (System Time and Time Zone)
The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone.
...@@ -29,21 +29,29 @@ Sets the system time. This API uses an asynchronous callback to return the resul ...@@ -29,21 +29,29 @@ Sets the system time. This API uses an asynchronous callback to return the resul
| time | number | Yes | Timestamp to set, in milliseconds. | | time | number | Yes | Timestamp to set, in milliseconds. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| -1 | The parameter check failed or permission denied or system error. |
**Example** **Example**
```js ```js
// Set the system time to 2021-01-20 02:36:25. // Set the system time to 2021-01-20 02:36:25.
let time = 1611081385000; let time = 1611081385000;
try { try {
systemTime.setTime(time, (error) => { systemTime.setTime(time, (error) => {
if (error) { if (error) {
console.info(`Failed to setting time. message:${error.message}, code:${error.code}`); console.info(`Failed to setting time. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in setting time`); }console.info(`Succeeded in setting time`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to set time. message:${e.message}, code:${e.code}`); console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -69,19 +77,27 @@ Sets the system time. This API uses a promise to return the result. ...@@ -69,19 +77,27 @@ Sets the system time. This API uses a promise to return the result.
| ------------------- | ------------------------- | | ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| -1 | The parameter check failed or permission denied or system error. |
**Example** **Example**
```js ```js
// Set the system time to 2021-01-20 02:36:25. // Set the system time to 2021-01-20 02:36:25.
let time = 1611081385000; let time = 1611081385000;
try { try {
systemTime.setTime(time).then(() => { systemTime.setTime(time).then(() => {
console.info(`Succeeded in setting time.`); console.info(`Succeeded in setting time.`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to setting time. message:${error.message}, code:${error.code}`); console.info(`Failed to setting time. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to set time. message:${e.message}, code:${e.code}`); console.info(`Failed to set time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -101,22 +117,30 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal ...@@ -101,22 +117,30 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------- | ---- | ------------------ | | -------- | -------------- | ---- | ------------------ |
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds (ns).<br>- **false**: in milliseconds (ms).| | isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time elapsed since the Unix epoch. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time elapsed since the Unix epoch. |
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getCurrentTime(true, (error, time) => { systemTime.getCurrentTime(true, (error, time) => {
if (error) { if (error) {
console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); console.info(`Failed to getting currentTime. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in getting currentTime : ${time}`); console.info(`Succeeded in getting currentTime: ${time}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -138,19 +162,27 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal ...@@ -138,19 +162,27 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal
| -------- | ----------- | ---- | ---------------------------------- | | -------- | ----------- | ---- | ---------------------------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time elapsed since the Unix epoch. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time elapsed since the Unix epoch. |
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getCurrentTime((error, time) => { systemTime.getCurrentTime((error, time) => {
if (error) { if (error) {
console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); console.info(`Failed to getting currentTime. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in getting currentTime : ${time}`); console.info(`Succeeded in getting currentTime : ${time}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -170,7 +202,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return ...@@ -170,7 +202,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------- | | ------ | ------- | ---- | ------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds (ns).<br>- **false**: in milliseconds (ms).| | isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
**Return value** **Return value**
...@@ -178,17 +210,25 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return ...@@ -178,17 +210,25 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return
| --------------------- | --------------------------- | | --------------------- | --------------------------- |
| Promise&lt;number&gt; | Promise used to return the time elapsed since the Unix epoch.| | Promise&lt;number&gt; | Promise used to return the time elapsed since the Unix epoch.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getCurrentTime().then((time) => { systemTime.getCurrentTime().then((time) => {
console.info(`Succeeded in getting currentTime : ${time}`); console.info(`Succeeded in getting currentTime : ${time}`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); console.info(`Failed to getting currentTime. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); console.info(`Failed to get currentTime. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -208,22 +248,30 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th ...@@ -208,22 +248,30 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------- | ---- | -------------------------- | | -------- | ---------- | ---- | -------------------------- |
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds (ns).<br>- **false**: in milliseconds (ms).| | isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getRealActiveTime(true, (error, time) => { systemTime.getRealActiveTime(true, (error, time) => {
if (error) { if (error) {
console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); console.info(`Failed to getting real active time. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in getting real active time : ${time}`); console.info(`Succeeded in getting real active time : ${time}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -245,19 +293,27 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th ...@@ -245,19 +293,27 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th
| -------- | -------------- | ---- | --------------------- | | -------- | -------------- | ---- | --------------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getRealActiveTime((error, time) => { systemTime.getRealActiveTime((error, time) => {
if (error) { if (error) {
console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); console.info(`Failed to getting real active time. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in getting real active time : ${time}`); console.info(`Succeeded in getting real active time : ${time}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -277,7 +333,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th ...@@ -277,7 +333,7 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ----------------------------------- | | ------ | ------- | ---- | ----------------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds (ns).<br>- **false**: in milliseconds (ms).| | isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
**Return value** **Return value**
...@@ -285,17 +341,25 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th ...@@ -285,17 +341,25 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th
| -------------- | -------------------------------- | | -------------- | -------------------------------- |
| Promise&lt;number&gt; | Promise used to return the time elapsed since system startup, excluding the deep sleep time.| | Promise&lt;number&gt; | Promise used to return the time elapsed since system startup, excluding the deep sleep time.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getRealActiveTime().then((time) => { systemTime.getRealActiveTime().then((time) => {
console.info(`Succeeded in getting real active time : ${time}`); console.info(`Succeeded in getting real active time : ${time}`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); console.info(`Failed to getting real active time. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); console.info(`Failed to get real active time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -315,22 +379,30 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th ...@@ -315,22 +379,30 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ------------------------------- | | -------- | --------------- | ---- | ------------------------------- |
| isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds (ns).<br>- **false**: in milliseconds (ms).| | isNano | boolean | Yes | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time. |
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getRealTime(true, (error, time) => { systemTime.getRealTime(true, (error, time) => {
if (error) { if (error) {
console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); console.info(`Failed to getting real time. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in getting real time : ${time}`); console.info(`Succeeded in getting real time : ${time}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -352,19 +424,27 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th ...@@ -352,19 +424,27 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th
| -------- | --------- | ---- | --------------------------- | | -------- | --------- | ---- | --------------------------- |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the time. |
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getRealTime((error, time) => { systemTime.getRealTime((error, time) => {
if (error) { if (error) {
console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); console.info(`Failed to getting real time. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in getting real time : ${time}`); console.info(`Succeeded in getting real time : ${time}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -384,7 +464,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th ...@@ -384,7 +464,7 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ---- | ------------------------------- | | ------ | ------- | ---- | ------------------------------- |
| isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds (ns).<br>- **false**: in milliseconds (ms).| | isNano | boolean | No | Whether the time to return is in nanoseconds.<br>- **true**: in nanoseconds.<br>- **false**: in milliseconds.|
**Return value** **Return value**
...@@ -392,17 +472,25 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th ...@@ -392,17 +472,25 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th
| --------------------- | ------------------------------- | | --------------------- | ------------------------------- |
| Promise&lt;number&gt; | Promise used to return the time elapsed since system startup, including the deep sleep time.| | Promise&lt;number&gt; | Promise used to return the time elapsed since system startup, including the deep sleep time.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getRealTime().then((time) => { systemTime.getRealTime().then((time) => {
console.info(`Succeeded in getting real time : ${time}`); console.info(`Succeeded in getting real time : ${time}`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); console.info(`Failed to getting real time. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); console.info(`Failed to get real time. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -423,20 +511,28 @@ Sets the system date. This API uses an asynchronous callback to return the resul ...@@ -423,20 +511,28 @@ Sets the system date. This API uses an asynchronous callback to return the resul
| date | Date | Yes | Target date to set. | | date | Date | Yes | Target date to set. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| -1 | The parameter check failed or permission denied or system error. |
**Example** **Example**
```js ```js
let date = new Date(); let date = new Date();
try { try {
systemTime.setDate(date, (error) => { systemTime.setDate(date, (error) => {
if (error) { if (error) {
console.info(`Failed to setting date. message:${error.message}, code:${error.code}`); console.info(`Failed to setting date. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in setting date.`); console.info(`Succeeded in setting date.`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to set date. message:${e.message}, code:${e.code}`); console.info(`Failed to set date. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -462,18 +558,26 @@ Sets the system date. This API uses a promise to return the result. ...@@ -462,18 +558,26 @@ Sets the system date. This API uses a promise to return the result.
| ------------------- | -------------------- | | ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| -1 | The parameter check failed or permission denied or system error. |
**Example** **Example**
```js ```js
let date = new Date(); let date = new Date();
try { try {
systemTime.setDate(date).then(() => { systemTime.setDate(date).then(() => {
console.info(`Succeeded in setting date.`); console.info(`Succeeded in setting date.`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to setting date. message:${error.message}, code:${error.code}`); console.info(`Failed to setting date. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to set date. message:${e.message}, code:${e.code}`); console.info(`Failed to set date. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -495,19 +599,27 @@ Obtains the current system date. This API uses an asynchronous callback to retur ...@@ -495,19 +599,27 @@ Obtains the current system date. This API uses an asynchronous callback to retur
| -------- | -------------- | ---- | --------------------- | | -------- | -------------- | ---- | --------------------- |
| callback | AsyncCallback&lt;Date&gt; | Yes | Callback used to return the current system date.| | callback | AsyncCallback&lt;Date&gt; | Yes | Callback used to return the current system date.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getDate((error, date) => { systemTime.getDate((error, date) => {
if (error) { if (error) {
console.info(`Failed to get date. message:${error.message}, code:${error.code}`); console.info(`Failed to get date. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in get date : ${date}`);; console.info(`Succeeded in get date : ${date}`);;
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get date. message:${e.message}, code:${e.code}`); console.info(`Failed to get date. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -529,17 +641,25 @@ Obtains the current system date. This API uses a promise to return the result. ...@@ -529,17 +641,25 @@ Obtains the current system date. This API uses a promise to return the result.
| ------------------- | ----------------------------------------- | | ------------------- | ----------------------------------------- |
| Promise&lt;Date&gt; | Promise used to return the current system date.| | Promise&lt;Date&gt; | Promise used to return the current system date.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getDate().then((date) => { systemTime.getDate().then((date) => {
console.info(`Succeeded in getting date : ${date}`); console.info(`Succeeded in getting date : ${date}`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to getting date. message:${error.message}, code:${error.code}`); console.info(`Failed to getting date. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get date. message:${e.message}, code:${e.code}`); console.info(`Failed to get date. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -560,19 +680,27 @@ Sets the system time zone. This API uses an asynchronous callback to return the ...@@ -560,19 +680,27 @@ Sets the system time zone. This API uses an asynchronous callback to return the
| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones). | | timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones). |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| -1 | The parameter check failed or permission denied or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.setTimezone('Asia/Shanghai', (error) => { systemTime.setTimezone('Asia/Shanghai', (error) => {
if (error) { if (error) {
console.info(`Failed to setting timezone. message:${error.message}, code:${error.code}`); console.info(`Failed to setting timezone. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in setting timezone.`); console.info(`Succeeded in setting timezone.`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); console.info(`Failed to set timezone. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -598,17 +726,25 @@ Sets the system time zone. This API uses a promise to return the result. ...@@ -598,17 +726,25 @@ Sets the system time zone. This API uses a promise to return the result.
| ------------------- | -------------------- | | ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| -1 | The parameter check failed or permission denied or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.setTimezone('Asia/Shanghai').then(() => { systemTime.setTimezone('Asia/Shanghai').then(() => {
console.info(`Succeeded in setting timezone.`); console.info(`Succeeded in setting timezone.`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to setting timezone. message:${error.message}, code:${error.code}`); console.info(`Failed to setting timezone. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); console.info(`Failed to set timezone. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -630,19 +766,27 @@ Obtains the system time zone. This API uses an asynchronous callback to return t ...@@ -630,19 +766,27 @@ Obtains the system time zone. This API uses an asynchronous callback to return t
| -------- | --------- | ---- | ------------------------ | | -------- | --------- | ---- | ------------------------ |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getTimezone((error, data) => { systemTime.getTimezone((error, data) => {
if (error) { if (error) {
console.info(`Failed to get timezone. message:${error.message}, code:${error.code}`); console.info(`Failed to get timezone. message: ${error.message}, code: ${error.code}`);
return; return;
} }
console.info(`Succeeded in get timezone : ${data}`);; console.info(`Succeeded in get timezone : ${data}`);;
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); console.info(`Failed to get timezone. message: ${e.message}, code: ${e.code}`);
} }
``` ```
...@@ -664,17 +808,25 @@ Obtains the system time zone. This API uses a promise to return the result. ...@@ -664,17 +808,25 @@ Obtains the system time zone. This API uses a promise to return the result.
| --------------------- | ------------------------------------- | | --------------------- | ------------------------------------- |
| Promise&lt;string&gt; | Promise used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| | Promise&lt;string&gt; | Promise used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).|
**Error codes**
For details about the error codes, see [Time and Time Zone Service Error Codes](../errorcodes/errorcode-time.md).
| ID| Error Message |
| -------- | ------------------------------------------- |
| -1 | The parameter check failed or system error. |
**Example** **Example**
```js ```js
try { try {
systemTime.getTimezone().then((data) => { systemTime.getTimezone().then((data) => {
console.info(`Succeeded in getting timezone: ${data}`); console.info(`Succeeded in getting timezone: ${data}`);
}).catch((error) => { }).catch((error) => {
console.info(`Failed to getting timezone. message:${error.message}, code:${error.code}`); console.info(`Failed to getting timezone. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); console.info(`Failed to get timezone. message: ${e.message}, code: ${e.code}`);
} }
``` ```
......
...@@ -1864,7 +1864,7 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -1864,7 +1864,7 @@ Obtains the area where this window cannot be displayed, for example, the system
| Name| Type| Mandatory| Description| | 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** **Return value**
...@@ -2500,7 +2500,7 @@ Disables listening for window size changes. ...@@ -2500,7 +2500,7 @@ Disables listening for window size changes.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------- | ---- | -------------------------------------------------------- | | -------- | ----------------------------- | ---- | -------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.| | 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** **Example**
...@@ -3006,7 +3006,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re ...@@ -3006,7 +3006,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re
| Name| Type| Mandatory| Description| | 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. | | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. |
**Error codes** **Error codes**
...@@ -3045,7 +3045,7 @@ Sets a color space for this window. This API uses a promise to return the result ...@@ -3045,7 +3045,7 @@ Sets a color space for this window. This API uses a promise to return the result
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| ---------- | ------------------------- | -- | ------------- | | ---------- | ------------------------- | -- | ------------- |
| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.| | colorSpace | [ColorSpace](#colorspace8) | Yes| Color space to set.|
**Return value** **Return value**
...@@ -3088,7 +3088,7 @@ Obtains the color space of this window. ...@@ -3088,7 +3088,7 @@ Obtains the color space of this window.
| Type| Description| | Type| Description|
| ------------------------- | ------------- | | ------------------------- | ------------- |
| [ColorSpace](#colorspace) | Color space obtained.| | [ColorSpace](#colorspace8) | Color space obtained.|
**Error codes** **Error codes**
...@@ -4631,7 +4631,7 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -4631,7 +4631,7 @@ Obtains the area where this window cannot be displayed, for example, the system
| Name | Type | Mandatory | Description | | 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. | | callback | AsyncCallback&lt;[AvoidArea](#avoidarea7)&gt; | Yes | Callback used to return the area. |
**Example** **Example**
...@@ -4664,7 +4664,7 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -4664,7 +4664,7 @@ Obtains the area where this window cannot be displayed, for example, the system
| Name | Type | Mandatory | Description | | 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** **Return value**
...@@ -5239,7 +5239,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re ...@@ -5239,7 +5239,7 @@ Sets a color space for this window. This API uses an asynchronous callback to re
| Name | Type | Mandatory | Description | | 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. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -5271,7 +5271,7 @@ Sets a color space for this window. This API uses a promise to return the result ...@@ -5271,7 +5271,7 @@ Sets a color space for this window. This API uses a promise to return the result
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------- | --------- | ------------------- | | ---------- | ------------------------- | --------- | ------------------- |
| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. | | colorSpace | [ColorSpace](#colorspace8) | Yes | Color space to set. |
**Return value** **Return value**
...@@ -5307,7 +5307,7 @@ Obtains the color space of this window. This API uses an asynchronous callback t ...@@ -5307,7 +5307,7 @@ Obtains the color space of this window. This API uses an asynchronous callback t
| Name | Type | Mandatory | Description | | 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** **Example**
...@@ -5338,7 +5338,7 @@ Obtains the color space of this window. This API uses a promise to return the re ...@@ -5338,7 +5338,7 @@ Obtains the color space of this window. This API uses a promise to return the re
| Type | Description | | 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** **Example**
......
...@@ -74,7 +74,7 @@ ...@@ -74,7 +74,7 @@
- [Vibrator Error Codes](errorcode-vibrator.md) - [Vibrator Error Codes](errorcode-vibrator.md)
- [System Parameter Error Codes](errorcode-system-parameterV9.md) - [System Parameter Error Codes](errorcode-system-parameterV9.md)
- [USB Error Codes](errorcode-usb.md) - [USB Error Codes](errorcode-usb.md)
- [Update Error Code](errorcode-update.md) - [Update Error Codes](errorcode-update.md)
- Customization Management - Customization Management
- [Enterprise Device Management Error Codes](errorcode-enterpriseDeviceManager.md) - [Enterprise Device Management Error Codes](errorcode-enterpriseDeviceManager.md)
- Utils - 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 @@ ...@@ -5,9 +5,9 @@
- [Transient Task Development](transient-task-dev-guide.md) - [Transient Task Development](transient-task-dev-guide.md)
- [Continuous Task Development](continuous-task-dev-guide.md) - [Continuous Task Development](continuous-task-dev-guide.md)
- [Work Scheduler Development](work-scheduler-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) - [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md)
- Agent-Powered Scheduled Reminder - Agent-Powered Scheduled Reminder
- [Agent-Powered Reminder Overview](reminder-agent-overview.md) - [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 # 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. 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 ## 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: 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 ## Selecting a Background Task
![Background Task Selection](public_sys-resources/bgtask_choice.png) ![Background Task Selection](figures/bgtask_choice.png)
## Transient Tasks ## Transient Tasks
...@@ -51,17 +51,17 @@ OpenHarmony provides 9 background modes for services that require continuous tas ...@@ -51,17 +51,17 @@ OpenHarmony provides 9 background modes for services that require continuous tas
**Table 1** Background modes for continuous tasks **Table 1** Background modes for continuous tasks
| Background Mode| Description| Hint in Notification Panel| Remarks| | 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.| - | | 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.| - | | audioPlayback | Audio output | An audio playback task is running. | - |
| audioRecording | Audio input| A recording task is running.| - | | audioRecording | Audio input | A recording task is running. | - |
| location | Positioning and navigation| A positioning task is running.| - | | location | Positioning and navigation | A positioning task is running. | - |
| bluetoothInteraction | Bluetooth transmission| A Bluetooth-related task is running.| - | | bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - |
| multiDeviceConnection | Distributed interconnection| A distributed 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| | 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| | 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| | taskKeeping | Computing task | A computing task is running | Effective only for specific devices |
### Restrictions on Using Continuous Tasks ### 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. - 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 ...@@ -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). - **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. - **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 | | Application Group | Work Scheduler Task Execution Frequency|
| --------------------|------------------------- | | ---------------------------------------- | ---------- |
| Active| At a minimum interval of 2 hours| | Active | At a minimum interval of 2 hours |
| Used every day| At a minimum interval of 4 hours| | Used every day | At a minimum interval of 4 hours |
| Frequently used| At a minimum interval of 24 hours| | Frequently used | At a minimum interval of 24 hours |
| Infrequently used| At a minimum interval of 48 hours| | Infrequently used | At a minimum interval of 48 hours |
| Restricted| Prohibited| | Restricted | Prohibited |
| Unused| Prohibited| | Unused | Prohibited |
| [Exemption group for efficiency resources](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | Unlimited| | [Exemption group for efficiency resources](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#resourcetype)| Unlimited |
- **WorkInfo setting** - **WorkInfo setting**
...@@ -110,25 +110,21 @@ An application or process is assigned the privileges associated with the obtaine ...@@ -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 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. * With the hardware resources, the application can still be woken up by related services to execute tasks when it is suspended in the background.
**Table 2** Efficiency resource types **Table 2** Efficiency resource types
| Name | Value | Description | | Name | Value | Description |
| ----------------------- | ---- | --------------------- | | -------------- | ---- | ------------------- |
| CPU | 1 | CPU resources, which prevent the application from being suspended. | | 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. | | 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. | | 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. | | 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. | | 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. | | 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.| | AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended. |
### Restrictions on Using Efficiency Resources ### Restrictions on Using Efficiency Resources
- Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application. - Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application.
- If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released. - If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released.
- The WORK_SCHEDULER resources can be requested and released by applications, but not by processes. - The WORK_SCHEDULER resources can be requested and released by applications, but not by processes.
- To use efficiency resources, an application must first submit a request to the application center to obtain corresponding privileges. - 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 @@ ...@@ -3,7 +3,7 @@
## When to Use ## 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. 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 ## Available APIs
...@@ -15,7 +15,7 @@ There is no time limit for a continuous task running in the background. To preve ...@@ -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. | | 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 **Table 2** Background modes
...@@ -34,152 +34,9 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA ...@@ -34,152 +34,9 @@ For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantA
## How to Develop ## 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). For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-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**.
```
"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).
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. 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 ...@@ -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 ```ts
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
@Entry @Entry
...@@ -220,7 +77,7 @@ struct Index { ...@@ -220,7 +77,7 @@ struct Index {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility", abilityName: "EntryAbility",
} }
], ],
// Type of the operation to perform after the notification is clicked. // Type of the operation to perform after the notification is clicked.
...@@ -290,14 +147,14 @@ struct Index { ...@@ -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 ```ts
import Ability from '@ohos.application.Ability' import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 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; let mContext = null;
...@@ -307,7 +164,7 @@ function startContinuousTask() { ...@@ -307,7 +164,7 @@ function startContinuousTask() {
wants: [ wants: [
{ {
bundleName: "com.example.myapplication", bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility", abilityName: "EntryAbility",
} }
], ],
// Type of the operation to perform after the notification is clicked. // Type of the operation to perform after the notification is clicked.
...@@ -381,7 +238,7 @@ function sendMsgCallback(data) { ...@@ -381,7 +238,7 @@ function sendMsgCallback(data) {
return new MySequenceable(10, "Callee test"); return new MySequenceable(10, "Callee test");
} }
export default class BgTaskAbility extends Ability { export default class BgTaskAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.info("[Demo] BgTaskAbility onCreate") console.info("[Demo] BgTaskAbility onCreate")
this.callee.on("test", sendMsgCallback); this.callee.on("test", sendMsgCallback);
...@@ -421,3 +278,146 @@ export default class BgTaskAbility extends Ability { ...@@ -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 @@ ...@@ -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. 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 | | 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. | | 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**.) | | 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. | | 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. | | 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. | | 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. | | 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 ## How to Develop
...@@ -51,9 +51,9 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -51,9 +51,9 @@ The agent-powered reminder feature provides APIs for publishing background remin
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
title:'this is title', // Reminder title. title: 'this is title', // Reminder title.
content:'this is content', // Reminder content. content: 'this is content', // Reminder content.
expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires. 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. 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. 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 ...@@ -94,10 +94,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
ringDuration: 5, // Ringing duration, in seconds. ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times. snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 5, // Reminder snooze interval, in seconds. 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. content:'this is content', // Reminder content.
expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires. 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. 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. 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. 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 ...@@ -131,10 +131,10 @@ The agent-powered reminder feature provides APIs for publishing background remin
ringDuration: 5, // Ringing duration, in seconds. ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times. snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 5, // Reminder snooze interval, in seconds. 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. content: 'this is content', // Reminder content.
expiredContent:'This reminder has expired', // Content to be displayed after the reminder expires. 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. 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. 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. 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 ...@@ -175,7 +175,3 @@ The agent-powered reminder feature provides APIs for publishing background remin
console.log("cancelReminder code: " + error.code + ", message: " + error.message); console.log("cancelReminder code: " + error.code + ", message: " + error.message);
}; };
``` ```
<!--no_check-->
\ No newline at end of file
...@@ -2,12 +2,11 @@ ...@@ -2,12 +2,11 @@
## When to Use ## 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. 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.
The calling of the **requestSuspendDelay** API when the application is running in the foreground does not affect the transient task quota of the application.
Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should cancel the transient task in a timely manner. 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. 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 ...@@ -19,67 +18,74 @@ Typical time-consuming tasks include saving status data to the local database, o
| API | Description | | 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. | | 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. | | cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. |
## How to Develop ## 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 ```js
import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
let delayInfo; let id; // ID of the suspension delay request.
let id; let delayTime; // Remaining duration for the suspension delay request.
// Request a suspension delay. // Request a suspension delay.
function requestSuspendDelay() { function requestSuspendDelay() {
let myReason = 'test requestSuspendDelay'; let myReason = 'test requestSuspendDelay'; // Reason for the suspension delay request.
delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspension delay will time out."); try {
// 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 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; 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. // Obtain the remaining duration before the application is suspended.
function getRemainingDelayTime() { async function getRemainingDelayTime() {
let delayTime = 0; try {
backgroundTaskManager.getRemainingDelayTime(id).then((res) => { await backgroundTaskManager.getRemainingDelayTime(id).then(res => {
console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); console.log('[backgroundTaskManager] promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
delayTime = res; }).catch(error => {
}).catch((err) => { console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); })
}); } catch (error) {
return delayTime; console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
}
} }
// Cancel the suspension delay. // Cancel the suspension delay.
function cancelSuspendDelay() { function cancelSuspendDelay() {
backgroundTaskManager.cancelSuspendDelay(id); backgroundTaskManager.cancelSuspendDelay(id);
} }
function performingLongRunningTask() { async function performingLongRunningTask() {
// Before executing the time-consuming task, call the API to request a transient task to delay the suspension. // Before executing a time-consuming task, call the API to request a transient task to delay the suspension.
requestSuspendDelay(); requestSuspendDelay();
// Obtain the available time quota through the getRemainingDelayTime() API.
let delayTime = getRemainingDelayTime();
if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming operation. // If required, obtain the available time quota through the getRemainingDelayTime() API.
// Handle the scenario where the time quota is insufficient. await getRemainingDelayTime();
cancelSuspendDelay(); if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming task.
return; // 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. // After the time-consuming task is executed, call the API to cancel the transient task.
cancelSuspendDelay(); cancelSuspendDelay();
} }
``` ```
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## 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 ## Available APIs
...@@ -14,21 +14,21 @@ startWork(work: WorkInfo): void; | Starts a Work Scheduler task. ...@@ -14,21 +14,21 @@ startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a Work Scheduler task. stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a Work Scheduler task.
getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result. getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result.
getWorkStatus(workId: number): Promise\<WorkInfo>; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result. getWorkStatus(workId: number): Promise\<WorkInfo>; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result.
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains Work Scheduler tasks. This API uses an asynchronous callback to return the result. obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains all the Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains Work Scheduler tasks. This API uses a promise to return the result. obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains all the Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): void;| Stops and clears Work Scheduler tasks. 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, callback: AsyncCallback\<void>): boolean;| Checks whether the last execution of the specified task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.
isLastWorkTimeOut(workId: number): Promise\<boolean>;| Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks. isLastWorkTimeOut(workId: number): Promise\<boolean>;| Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.
**Table 2** WorkInfo parameters **Table 2** WorkInfo parameters
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 Name| Type|Description
---------------------------------------------------------|-----------------------------------------|--------------------------------------------------------- ---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
workId| number | Work ID. Mandatory. workId| number | ID of the Work Scheduler task. Mandatory.
bundleName| string | Name of the Work Scheduler task bundle. Mandatory. bundleName| string | Bundle name of the Work Scheduler task. Mandatory.
abilityName| string | Name of the component to be notified by a Work Scheduler callback. 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. networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.
isCharging| boolean | Whether the device is charging. isCharging| boolean | Whether the device is charging.
chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type. chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.
...@@ -42,26 +42,27 @@ parameters | {[key: string]: any} |Carried parameters. ...@@ -42,26 +42,27 @@ parameters | {[key: string]: any} |Carried parameters.
**Table 3** Work Scheduler callbacks **Table 3** Work Scheduler callbacks
Name | Description API | Description
---------------------------------------------------------|----------------------------------------- ---------------------------------------------------------|-----------------------------------------
onWorkStart(work: WorkInfo): void | Triggered when the Work Scheduler task starts. onWorkStart(work: WorkInfo): void | Called when the Work Scheduler task starts.
onWorkStop(work: WorkInfo): void | Triggered when the Work Scheduler task stops. onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops.
### How to Develop ### How to Develop
1. Import the modules. 1. Import the modules.
Import the **workScheduler** package to implement registration: Import the **workScheduler** module.
```js
import workScheduler from '@ohos.resourceschedule.workScheduler'; ```js
``` import workScheduler from '@ohos.resourceschedule.workScheduler';
```
Import the **WorkSchedulerExtensionAbility** package to implement callback: Import the **WorkSchedulerExtensionAbility** module.
```js ```js
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; 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 ```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'; import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
...@@ -77,7 +78,7 @@ export default class MyExtension extends WorkSchedulerExtensionAbility { ...@@ -77,7 +78,7 @@ export default class MyExtension extends WorkSchedulerExtensionAbility {
``` ```
3. Register a Work Scheduler task. 3. Start a Work Scheduler task.
```ts ```ts
import workScheduler from '@ohos.resourceschedule.workScheduler'; import workScheduler from '@ohos.resourceschedule.workScheduler';
...@@ -105,7 +106,7 @@ try{ ...@@ -105,7 +106,7 @@ try{
``` ```
4. Cancel the Work Scheduler task. 4. Stop the Work Scheduler task.
```ts ```ts
import workScheduler from '@ohos.resourceschedule.workScheduler'; import workScheduler from '@ohos.resourceschedule.workScheduler';
...@@ -152,7 +153,7 @@ try{ ...@@ -152,7 +153,7 @@ try{
``` ```
6. Obtain all Work Scheduler tasks. 6. Obtain all the Work Scheduler tasks.
```ts ```ts
try{ try{
...@@ -168,7 +169,7 @@ try{ ...@@ -168,7 +169,7 @@ try{
} }
``` ```
7. Stop and clear Work Scheduler tasks. 7. Stop and clear all the Work Scheduler tasks.
```ts ```ts
try{ try{
...@@ -179,7 +180,7 @@ 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 ```ts
try{ 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. ...@@ -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.createWindow** to create a subwindow.
- Call **window.findWindow** to find an available subwindow. - Call **window.findWindow** to find an available subwindow.
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
let windowClass = null; let windowClass = null;
// Method 1: Create a subwindow. // Method 1: Create a subwindow.
let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP, ctx: this.context}; let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP, ctx: this.context};
window.createWindow(config, (err, data) => { window.createWindow(config, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data; windowClass = data;
}); });
// Method 2: Find a subwindow. // Method 2: Find a subwindow.
window.findWindow("subWindow", (err, data) => { window.findWindow("subWindow", (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data));
windowClass = data; windowClass = data;
}); });
``` ```
2. Set the properties of the subwindow. 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> # Commonlibrary Development Guidelines<a name="EN-US_TOPIC_0000001059307279"></a>
## Overview
## Available APIs<a name="section1633115419401"></a> 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:
**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:
``` ```
// Open a file and write data. /commonlibrary
char fileName[] = "testfile"; ├── c_utils # Enhanced basic C/C++ library for developers
static const char def[] = "utils_file_operation implement."; ├── ets_utils # Enhanced basic JS library for developers
int fd = UtilsFileOpen(fileName, O_RDWR_FS | O_CREAT_FS | O_TRUNC_FS, 0); └── utils_lite # Basic tools for liteOS, including C and JS.
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);
``` ```
Features provided by every repositories are listed here:
## How to Develop<a name="section17450172710292"></a> **c_utils**
### 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")
- 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
``` **utils_lite**
./bin/os_dump --help
```
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
``` ## Development Guidelines<a name="section1633115419401"></a>
./bin/os_dump -l
```
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> # Commonlibrary Subsystem FAQ
![](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") ## 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 @@ ...@@ -3,7 +3,14 @@
## Introduction<a name="section11660541593"></a> ## 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** **c_utils**
...@@ -24,15 +31,8 @@ The **commonlibrary** subsystem provides common enhanced APIs for development in ...@@ -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 - Hardware Abstraction Layer (HAL) APIs for performing operations on standard files
- APIs for internal functions, such as the timer - APIs for internal functions, such as the timer
## Related Documents<a name="section17271017133915"></a>
## Directory Structure<a name="section17271017133915"></a> [Commonlibrary Development Guidelines](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/subsys-utils-guide.md)
```
/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.
```
## Repositories Involved<a name="section1249817110914"></a> ## Repositories Involved<a name="section1249817110914"></a>
......
...@@ -18,14 +18,14 @@ After change: ...@@ -18,14 +18,14 @@ After change:
| Module | Class | Method/Attribute/Enumeration/Constant | Change Type| | 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, callback: AsyncCallback\<number>): void | Changed |
| @ohos.systemTimer | systemTimer | function createTimer(options: TimerOptions): Promise<number> | 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, callback: AsyncCallback\<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function startTimer(timer: number, triggerTime: number): Promise<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, callback: AsyncCallback\<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function stopTimer(timer: number): Promise<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, callback: AsyncCallback\<void>): void | Changed |
| @ohos.systemTimer | systemTimer | function destroyTimer(timer: number): Promise<void> | Changed | | @ohos.systemTimer | systemTimer | function destroyTimer(timer: number): Promise\<void> | Changed |
**Adaptation Guide** **Adaptation Guide**
...@@ -34,232 +34,303 @@ Refer to the code below to capture errors when **systemTimer** APIs are called i ...@@ -34,232 +34,303 @@ Refer to the code below to capture errors when **systemTimer** APIs are called i
createTimer callback mode: createTimer callback mode:
**Example**: **Example**
```js ```js
export default { export default {
systemTimer () { systemTimer () {
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat: false repeat: false
}; };
try { try {
systemTimer.createTimer(options, (error, data) => { systemTimer.createTimer(options, (error, timerId) => {
if (error) { if (error) {
// Capture the permission denial error. // Capture the permission denial error.
console.info(`Failed to create timer. message:${error.message}, code:${error.code}`); 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}`);
} }
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: createTimer promise mode:
**Example**: **Example**
```js ```js
export default { export default {
systemTimer () { systemTimer () {
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat: false repeat: false
}; };
try { try {
systemTimer.createTimer(options).then((data) => { systemTimer.createTimer(options).then((timerId) => {
console.info(`Succeeded in creating timer. Data:` + data); console.info(`Succeeded in creating timer. timerId: ${timerId}`);
}).catch((error) => { }).catch((error) => {
// Capture the permission denial error. // Capture the permission denial error.
console.info(`Failed to create timer. message:${error.message}, code:${error.code}`); console.info(`Failed to create timer. message: ${error.message}, code: ${error.code}`);
}); });
} catch(e) { } catch(e) {
// Capture the parameter verification error. // Capture the parameter verification error.
console.info(`Failed to create timer. message:${e.message}, code:${e.code}`); console.info(`Failed to create timer. message: ${e.message}, code: ${e.code}`);
}
} }
}
} }
``` ```
startTimer callback mode: startTimer callback mode:
**Example**: **Example**
```js ```js
export default { export default {
async systemTimer () { async systemTimer () {
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false repeat:false
} }
let timerId = await systemTimer.createTimer(options); let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime(); let triggerTime = new Date().getTime();
triggerTime += 3000; triggerTime += 3000;
try { try {
systemTimer.startTimer(timerId, triggerTime, (error) => { systemTimer.startTimer(timerId, triggerTime, (error) => {
if (error) { if (error) {
// Capture the permission denial error. // Capture the permission denial error.
console.error(`Failed to start timer. message:${error.message}, code:${error.code}`); 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}`);
} }
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`);
} }
}
} }
``` ```
startTimer promise mode: startTimer promise mode:
**Example**: **Example**
```js ```js
export default { export default {
async systemTimer (){ async systemTimer (){
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false repeat:false
} }
let timerId = await systemTimer.createTimer(options); let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime(); let triggerTime = new Date().getTime();
triggerTime += 3000; triggerTime += 3000;
try { try {
systemTimer.startTimer(timerId, triggerTime).then((data) => { systemTimer.startTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in startting timer. Data:` + data); console.log(`Succeeded in startting timer. Data:` + data);
}).catch((error) => { }).catch((error) => {
// Capture the permission denial error. // Capture the permission denial error.
console.info(`Failed to start timer. message:${error.message}, code:${error.code}`); console.info(`Failed to start timer. message: ${error.message}, code: ${error.code}`);
}); });
} catch (e) { } catch (e) {
// Capture the parameter verification error. // Capture the parameter verification error.
console.info(`Failed to start timer. message:${e.message}, code:${e.code}`); console.info(`Failed to start timer. message: ${e.message}, code: ${e.code}`);
}
} }
}
} }
``` ```
stopTimer callback mode: stopTimer callback mode:
**Example**: **Example**
```js ```js
export default { export default {
async systemTimer () { async systemTimer () {
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false repeat:false
} }
let timerId = await systemTimer.createTimer(options); let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime(); let triggerTime = new Date().getTime();
triggerTime += 3000; triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime); systemTimer.startTimer(timerId, triggerTime);
try { try {
systemTimer.stopTimer(timerId, triggerTime, (error) => { systemTimer.stopTimer(timerId, triggerTime, (error) => {
if (error) { if (error) {
// Capture the permission denial error. // Capture the permission denial error.
console.error(`Failed to stop timer. message:${error.message}, code:${error.code}`); 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}`);
} }
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`);
} }
} }
}git
``` ```
stopTimer promise mode: stopTimer promise mode:
**Example**: **Example**
```js ```js
export default { export default {
async systemTimer (){ async systemTimer (){
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false repeat:false
} }
let timerId = await systemTimer.createTimer(options); let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime(); let triggerTime = new Date().getTime();
triggerTime += 3000; triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime); systemTimer.startTimer(timerId, triggerTime);
try { try {
systemTimer.stopTimer(timerId, triggerTime).then((data) => { systemTimer.stopTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in stop timer. Data:` + data); console.log(`Succeeded in stop timer. Data:` + data);
}).catch((error) => { }).catch((error) => {
// Capture the permission denial error. // Capture the permission denial error.
console.info(`Failed to stop timer. message:${error.message}, code:${error.code}`); console.info(`Failed to stop timer. message: ${error.message}, code: ${error.code}`);
}); });
} catch (e) { } catch (e) {
// Capture the parameter verification error. // Capture the parameter verification error.
console.info(`Failed to stop timer. message:${e.message}, code:${e.code}`); console.info(`Failed to stop timer. message: ${e.message}, code: ${e.code}`);
}
} }
}
} }
``` ```
destroyTimer callback mode: destroyTimer callback mode:
**Example**: **Example**
```js ```js
export default { export default {
async systemTimer () { async systemTimer () {
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false repeat:false
} }
let timerId = await systemTimer.createTimer(options); let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime(); let triggerTime = new Date().getTime();
triggerTime += 3000; triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime); systemTimer.startTimer(timerId, triggerTime);
systemTimer.stopTimer(timerId); systemTimer.stopTimer(timerId);
try { try {
systemTimer.destroyTimer(timerId, triggerTime, (error) => { systemTimer.destroyTimer(timerId, triggerTime, (error) => {
if (error) { if (error) {
// Capture the permission denial error. // Capture the permission denial error.
console.error(`Failed to destroy timer. message:${error.message}, code:${error.code}`); 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}`);
} }
});
} catch (e) {
// Capture the parameter verification error.
console.info(`Failed to destroy timer. message: ${e.message}, code: ${e.code}`);
} }
}
} }
``` ```
destroyTimer promise mode: destroyTimer promise mode:
**Example**: **Example**
```js ```js
export default { export default {
async systemTimer (){ async systemTimer (){
let options = { let options = {
type: systemTimer.TIMER_TYPE_REALTIME, type: systemTimer.TIMER_TYPE_REALTIME,
repeat:false repeat:false
} }
let timerId = await systemTimer.createTimer(options); let timerId = await systemTimer.createTimer(options);
let triggerTime = new Date().getTime(); let triggerTime = new Date().getTime();
triggerTime += 3000; triggerTime += 3000;
systemTimer.startTimer(timerId, triggerTime); systemTimer.startTimer(timerId, triggerTime);
systemTimer.stopTimer(timerId); systemTimer.stopTimer(timerId);
try { try {
systemTimer.destroyTimer(timerId, triggerTime).then((data) => { systemTimer.destroyTimer(timerId, triggerTime).then((data) => {
console.log(`Succeeded in destroy timer. Data:` + data); console.log(`Succeeded in destroy timer. Data:` + data);
}).catch((error) => { }).catch((error) => {
// Capture the permission denial error. // Capture the permission denial error.
console.info(`Failed to destroy timer. message:${error.message}, code:${error.code}`); console.info(`Failed to destroy timer. message: ${error.message}, code: ${error.code}`);
}); });
} catch (e) { } catch (e) {
// Capture the parameter verification error. // Capture the parameter verification error.
console.info(`Failed to destroy timer. message:${e.message}, code:${e.code}`); 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 @@ ...@@ -69,6 +69,7 @@
- [Native API的相关指导](napi/Readme-CN.md) - [Native API的相关指导](napi/Readme-CN.md)
- 工具 - 工具
- [DevEco Studio(OpenHarmony)使用指南](quick-start/deveco-studio-user-guide-for-openharmony.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) - [示例代码](https://gitee.com/openharmony/applications_app_samples/blob/master/README_zh.md)
- [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs/blob/master/README.md)
......
...@@ -60,13 +60,7 @@ ...@@ -60,13 +60,7 @@
} catch (error) { } catch (error) {
console.info(`explicit start ability failed with ${error.code}`) 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 @@ ...@@ -67,7 +67,7 @@
- [获取应用开发路径](#获取应用开发路径) - [获取应用开发路径](#获取应用开发路径)
- [获取和修改加密分区](#获取和修改加密分区) - [获取和修改加密分区](#获取和修改加密分区)
- [创建其他应用或其他Module的Context](#创建其他应用或其他module的context) - [创建其他应用或其他Module的Context](#创建其他应用或其他module的context)
- [订阅进程内Ability生命周期变化](#订阅进程内ability生命周期变化) - [订阅进程内UIAbility生命周期变化](#订阅进程内uiability生命周期变化)
### 获取应用开发路径 ### 获取应用开发路径
...@@ -106,12 +106,12 @@ ...@@ -106,12 +106,12 @@
| 属性 | 路径 | | 属性 | 路径 |
| -------- | -------- | | -------- | -------- |
| bundleCodeDir | {路径前缀}/el1/bundle/ | | bundleCodeDir | {路径前缀}/el1/bundle/ |
| cacheDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**cache/ | | cacheDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/cache/ |
| filesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**files/ | | filesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/files/ |
| preferencesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**preferences/ | | preferencesDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/preferences/ |
| tempDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}/**temp/ | | tempDir | {路径前缀}/{加密等级}/base/**haps/{moduleName}**/temp/ |
| databaseDir | {路径前缀}/{加密等级}/database/**{moduleName}/** | | databaseDir | {路径前缀}/{加密等级}/database/**{moduleName}**/ |
| distributedFilesDir | {路径前缀}/el2/distributedFiles/**{moduleName}/** | | distributedFilesDir | {路径前缀}/el2/distributedFiles/**{moduleName}**/ |
获取应用开发路径的示例代码如下所示。 获取应用开发路径的示例代码如下所示。
...@@ -133,6 +133,9 @@ export default class EntryAbility extends UIAbility { ...@@ -133,6 +133,9 @@ export default class EntryAbility extends UIAbility {
} }
``` ```
> **说明:**
>
> 示例代码获取到的是应用开发路径的沙箱路径。其对应的绝对路径,在创建或者修改文件之后,可以在`hdc shell`中,通过`find / -name <文件名称>`命令查找获取。
### 获取和修改加密分区 ### 获取和修改加密分区
...@@ -226,11 +229,11 @@ export default class EntryAbility extends UIAbility { ...@@ -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 ```ts
...@@ -244,36 +247,36 @@ export default class EntryAbility extends UIAbility { ...@@ -244,36 +247,36 @@ export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityCreate(ability) { onAbilityCreate(uiability) {
console.info(TAG, "onAbilityCreate ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityCreate uiability:" + JSON.stringify(uiability));
}, },
onWindowStageCreate(ability, windowStage) { onWindowStageCreate(uiability, windowStage) {
console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageCreate uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
}, },
onWindowStageActive(ability, windowStage) { onWindowStageActive(uiability, windowStage) {
console.info(TAG, "onWindowStageActive ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageActive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage));
}, },
onWindowStageInactive(ability, windowStage) { onWindowStageInactive(uiability, windowStage) {
console.info(TAG, "onWindowStageInactive ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageInactive uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage));
}, },
onWindowStageDestroy(ability, windowStage) { onWindowStageDestroy(uiability, windowStage) {
console.info(TAG, "onWindowStageDestroy ability:" + JSON.stringify(ability)); console.info(TAG, "onWindowStageDestroy uiability:" + JSON.stringify(uiability));
console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage));
}, },
onAbilityDestroy(ability) { onAbilityDestroy(uiability) {
console.info(TAG, "onAbilityDestroy ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityDestroy uiability:" + JSON.stringify(uiability));
}, },
onAbilityForeground(ability) { onAbilityForeground(uiability) {
console.info(TAG, "onAbilityForeground ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityForeground uiability:" + JSON.stringify(uiability));
}, },
onAbilityBackground(ability) { onAbilityBackground(uiability) {
console.info(TAG, "onAbilityBackground ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityBackground uiability:" + JSON.stringify(uiability));
}, },
onAbilityContinue(ability) { onAbilityContinue(uiability) {
console.info(TAG, "onAbilityContinue ability:" + JSON.stringify(ability)); console.info(TAG, "onAbilityContinue uiability:" + JSON.stringify(uiability));
} }
} }
// 1. 通过context属性获取applicationContext // 1. 通过context属性获取applicationContext
......
...@@ -9,7 +9,7 @@ ExtensionAbility组件是基于特定场景(例如服务卡片、输入法等 ...@@ -9,7 +9,7 @@ ExtensionAbility组件是基于特定场景(例如服务卡片、输入法等
- [FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md):FORM类型的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组件,提供对输入法框架的管理,包括隐藏输入法、查询已安装的输入法列表和显示输入法选择对话框。 - [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod.md):INPUT_METHOD类型的ExtensionAbility组件,提供对输入法框架的管理,包括隐藏输入法、查询已安装的输入法列表和显示输入法选择对话框。
......
...@@ -9,7 +9,7 @@ ...@@ -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模型的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模型的线程模型以及几种常用的线程间通信方式。 | [线程间通信](itc-fa-overview.md) |
| 任务管理 | 本章节介绍了FA模型中任务管理的基本概念和典型场景。 | [任务管理](mission-management-fa.md) | | 任务管理 | 本章节介绍了FA模型中任务管理的基本概念和典型场景。 | [任务管理](mission-management-fa.md) |
| 应用配置文件 | 本章节介绍FA模型中应用配置文件的开发要求。 | [FA模型应用配置文件](config-file-fa.md) | | 应用配置文件 | 本章节介绍FA模型中应用配置文件的开发要求。 | [FA模型应用配置文件](config-file-fa.md) |
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
- [Context](application-context-stage.md) - [Context](application-context-stage.md)
在Stage模型上,Context及其派生类向开发者提供在运行期可以调用的各种能力。UIAbility组件和各种ExtensionAbility派生类都有各自不同的Context类,他们都继承自基类Context,但是各自又根据所属组件,提供不同的能力。 在Stage模型上,Context及其派生类向开发者提供在运行期可以调用的各种资源和能力。UIAbility组件和各种ExtensionAbility派生类都有各自不同的Context类,他们都继承自基类Context,但是各自又根据所属组件,提供不同的能力。
- [AbilityStage](abilitystage.md) - [AbilityStage](abilitystage.md)
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
启动远程PageAbility同样通过featureAbility中的startAbility接口实现。 启动远程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开发。 由于当前DeviceManager的getTrustedDeviceListSync接口仅对系统应用开放,故现阶段非系统应用无法获取其他设备信息,无远程启动设备选择入口,远程启动Ability开发。
......
...@@ -8,7 +8,7 @@ OpenHarmony相机模块支持相机业务的开发,开发者可以通过已开 ...@@ -8,7 +8,7 @@ OpenHarmony相机模块支持相机业务的开发,开发者可以通过已开
- **相机静态能力**:用于描述相机的固有能力的一系列参数,比如朝向、支持的分辨率等信息。 - **相机静态能力**:用于描述相机的固有能力的一系列参数,比如朝向、支持的分辨率等信息。
- **物理相机**:物理相机就是独立的实体摄像头设备。物理相机ID是用于标志每个物理摄像头的唯一字串。 - **物理相机**:物理相机就是独立的实体摄像头设备。物理相机ID是用于标志每个物理摄像头的唯一字串。
- **异步操作**:为保证UI线程不被阻塞,大部分Camera调用都是异步的。对于每个API均提供了callback函数和Promise函数。 - **异步操作**:为保证UI线程不被阻塞,部分Camera接口采用异步调用方式。异步方式API均提供了callback函数和Promise函数。
## 开发步骤 ## 开发步骤
...@@ -60,73 +60,99 @@ import media from '@ohos.multimedia.media' ...@@ -60,73 +60,99 @@ import media from '@ohos.multimedia.media'
// 创建CameraManager对象 // 创建CameraManager对象
context: any = getContext(this) context: any = getContext(this)
let cameraManager = await camera.getCameraManager(this.context) let cameraManager = camera.getCameraManager(this.context)
if (!cameraManager) { 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() let cameraArray = cameraManager.getSupportedCameras();
if (!cameraArray) { if (cameraArray.length <= 0) {
console.error('Failed to get the cameras'); console.error("cameraManager.getSupportedCameras error")
} return;
}
for (let index = 0; index < cameraArray.length; index++) { for (let index = 0; index < cameraArray.length; index++) {
console.log('cameraId : ' + cameraArray[index].cameraId) // 获取相机ID console.log('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID
console.log('cameraPosition : ' + cameraArray[index].cameraPosition) // 获取相机位置 console.log('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置
console.log('cameraType : ' + cameraArray[index].cameraType) // 获取相机类型 console.log('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型
console.log('connectionType : ' + cameraArray[index].connectionType) // 获取相机连接类型 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(); await cameraInput.open();
// 获取相机设备支持的输出流能力 // 获取相机设备支持的输出流能力
let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]); let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]);
if (!cameraOutputCap) { if (!cameraOutputCap) {
console.error("outputCapability outputCapability == null || undefined") console.error("cameraManager.getSupportedOutputCapability error")
} else { return;
console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
} }
console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
let previewProfilesArray = cameraOutputCap.GetPreviewProfiles(); let previewProfilesArray = cameraOutputCap.previewProfiles;
if (!previewProfilesArray) { if (!previewProfilesArray) {
console.error("createOutput previewProfilesArray == null || undefined") console.error("createOutput previewProfilesArray == null || undefined")
} }
let photoProfilesArray = cameraOutputCap.GetPhotoProfiles(); let photoProfilesArray = cameraOutputCap.photoProfiles;
if (!photoProfilesArray) { if (!photoProfilesArray) {
console.error("createOutput photoProfilesArray == null || undefined") console.error("createOutput photoProfilesArray == null || undefined")
} }
let videoProfilesArray = cameraOutputCap.GetVideoProfiles(); let videoProfilesArray = cameraOutputCap.videoProfiles;
if (!videoProfilesArray) { if (!videoProfilesArray) {
console.error("createOutput videoProfilesArray == null || undefined") console.error("createOutput videoProfilesArray == null || undefined")
} }
let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType(); let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes;
if (!metadataObjectTypesArray) { if (!metadataObjectTypesArray) {
console.error("createOutput metadataObjectTypesArray == null || undefined") console.error("createOutput metadataObjectTypesArray == null || undefined")
} }
// 创建预览输出流,其中参数 surfaceId 参考下面 XComponent 组件,预览流为XComponent组件提供的surface // 创建预览输出流,其中参数 surfaceId 参考下面 XComponent 组件,预览流为XComponent组件提供的surface
let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) let previewOutput
if (!previewOutput) { try {
previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
} catch (error) {
console.error("Failed to create the PreviewOutput instance.") console.error("Failed to create the PreviewOutput instance.")
} }
// 监听预览输出错误信息
previewOutput.on('error', (error) => {
console.log(`Preview output error code: ${error.code}`);
})
// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 // 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置
let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
// 获取照片显示SurfaceId // 获取照片显示SurfaceId
let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
// 创建拍照输出流 // 创建拍照输出流
let photoOutput = await cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) let photoOutput
if (!photoOutput) { try {
console.error('Failed to create the PhotoOutput instance.'); photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
return; } catch (error) {
console.error('Failed to createPhotoOutput errorCode = ' + error.code);
} }
// 创建视频录制的参数 // 创建视频录制的参数
...@@ -169,11 +195,17 @@ videoRecorder.getInputSurface().then((id) => { ...@@ -169,11 +195,17 @@ videoRecorder.getInputSurface().then((id) => {
}) })
// 创建VideoOutput对象 // 创建VideoOutput对象
let videoOutput = await cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId) let videoOutput
if (!videoOutput) { try {
console.error('Failed to create the videoOutput instance.'); videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
return; } 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。 预览流、拍照流和录像流的输入均需要提前创建surface,其中预览流为XComponent组件提供的surface,拍照流为ImageReceiver提供的surface,录像流为VideoRecorder的surface。
...@@ -247,24 +279,45 @@ function getVideoRecorderSurface() { ...@@ -247,24 +279,45 @@ function getVideoRecorderSurface() {
```typescript ```typescript
//创建会话 //创建会话
let captureSession = await camera.createCaptureSession() let captureSession
if (!captureSession) { try {
console.error('Failed to create the CaptureSession instance.'); captureSession = cameraManager.createCaptureSession()
return; } 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() await captureSession.commitConfig()
...@@ -282,13 +335,25 @@ await captureSession.start().then(() => { ...@@ -282,13 +335,25 @@ await captureSession.start().then(() => {
await captureSession.stop() 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() await captureSession.commitConfig()
...@@ -303,71 +368,65 @@ await captureSession.start().then(() => { ...@@ -303,71 +368,65 @@ await captureSession.start().then(() => {
```typescript ```typescript
// 判断设备是否支持闪光灯 // 判断设备是否支持闪光灯
let flashStatus = await captureSession.hasFlash() let flashStatus
if (!flashStatus) { try {
console.error('Failed to check whether the device has the flash mode.'); flashStatus = captureSession.hasFlash()
} catch (error) {
console.error('Failed to hasFlash. errorCode = ' + error.code);
} }
console.log('Promise returned with the flash light support status:' + flashStatus); console.log('Promise returned with the flash light support status:' + flashStatus);
if (flashStatus) { if (flashStatus) {
// 判断是否支持自动闪光灯模式 // 判断是否支持自动闪光灯模式
let flashModeStatus let flashModeStatus
captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => { try {
if (err) { let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO)
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);
flashModeStatus = status flashModeStatus = status
}) } catch (error) {
console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code);
}
if(flashModeStatus) { if(flashModeStatus) {
// 设置自动闪光灯模式 // 设置自动闪光灯模式
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => { try {
if (err) { captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO)
console.error('Failed to set the flash mode ${err.message}'); } catch (error) {
return; console.error('Failed to set the flash mode. errorCode = ' + error.code);
} }
console.log('Callback returned with the successful execution of setFlashMode.');
})
} }
} }
// 判断是否支持连续自动变焦模式 // 判断是否支持连续自动变焦模式
let focusModeStatus let focusModeStatus
captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => { try {
if (err) { let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
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);
focusModeStatus = status focusModeStatus = status
}) } catch (error) {
console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code);
}
if (focusModeStatus) { if (focusModeStatus) {
// 设置连续自动变焦模式 // 设置连续自动变焦模式
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => { try {
if (err) { captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
console.error('Failed to set the focus mode ${err.message}'); } catch (error) {
return; console.error('Failed to set the focus mode. errorCode = ' + error.code);
} }
console.log('Callback returned with the successful execution of setFocusMode.');
})
} }
// 获取相机支持的可变焦距比范围 // 获取相机支持的可变焦距比范围
let zoomRatioRange = await captureSession.getZoomRatioRange() let zoomRatioRange
if (!zoomRatioRange) { try {
console.error('Failed to get the zoom ratio range.'); zoomRatioRange = captureSession.getZoomRatioRange()
return; } catch (error) {
console.error('Failed to get the zoom ratio range. errorCode = ' + error.code);
} }
// 设置可变焦距比 // 设置可变焦距比
captureSession.setZoomRatio(zoomRatioRange[0], async (err) => { try {
if (err) { captureSession.setZoomRatio(zoomRatioRange[0])
console.error('Failed to set the zoom ratio value ${err.message}'); } catch (error) {
return; console.error('Failed to set the zoom ratio value. errorCode = ' + error.code);
} }
console.log('Callback returned with the successful execution of setZoomRatio.');
})
``` ```
#### 拍照 #### 拍照
...@@ -428,7 +487,7 @@ videoOutput.stop((err) => { ...@@ -428,7 +487,7 @@ videoOutput.stop((err) => {
captureSession.stop() captureSession.stop()
// 释放相机输入流 // 释放相机输入流
cameraInput.release() cameraInput.close()
// 释放预览输出流 // 释放预览输出流
previewOutput.release() previewOutput.release()
...@@ -449,4 +508,4 @@ captureSession = null ...@@ -449,4 +508,4 @@ captureSession = null
## 流程图 ## 流程图
应用使用相机的流程示意图如下 应用使用相机的流程示意图如下
![camera_framework process](figures/camera_framework_process.jpg) ![camera_framework process](figures/camera_framework_process.png)
\ No newline at end of file \ No newline at end of file
...@@ -46,33 +46,77 @@ struct bindPopupPage { ...@@ -46,33 +46,77 @@ struct bindPopupPage {
## 状态变量数据类型声明使用限制 ## 状态变量数据类型声明使用限制
@State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。 1. 所有的状态装饰器变量需要显式声明变量类型,不允许声明any,不支持Date数据类型。
示例: 示例:
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct IndexPage { struct DatePickerExample {
//错误写法: @State message: string | Resource = 'Hello World' //错误写法: @State isLunar: any = false
@State message: string = 'Hello World' @State isLunar: boolean = false
//错误写法: @State selectedDate: Date = new Date('2021-08-08')
build() { private selectedDate: Date = new Date('2021-08-08')
Row() {
Column() { build() {
Text(`${this.message}`) Column() {
.fontSize(50) Button('切换公历农历')
.fontWeight(FontWeight.Bold) .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 { ...@@ -98,6 +142,8 @@ struct IndexPage {
| @Link | 禁止 | 必须 | | @Link | 禁止 | 必须 |
| @StorageLink | 必须 | 禁止 | | @StorageLink | 必须 | 禁止 |
| @StorageProp | 必须 | 禁止 | | @StorageProp | 必须 | 禁止 |
| @LocalStorageLink | 必须 | 禁止 |
| @LocalStorageProp | 必须 | 禁止 |
| @Provide | 必须 | 可选 | | @Provide | 必须 | 可选 |
| @Consume | 禁止 | 禁止 | | @Consume | 禁止 | 禁止 |
| @ObjectLink | 禁止 | 必须 | | @ObjectLink | 禁止 | 必须 |
...@@ -111,25 +157,77 @@ struct IndexPage { ...@@ -111,25 +157,77 @@ struct IndexPage {
通过构造函数方法初始化成员变量,需要遵循如下规则: 通过构造函数方法初始化成员变量,需要遵循如下规则:
| 从父组件中的变量(下)到子组件中的变量(右) | @State | @Link | @Prop | 常规变量 | | **从父组件中的变量(右)到子组件中的变量(下)** | **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
| -------------------------------------------- | ------ | ------ | ------ | -------- | |---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
| @State | 不允许 | 允许 | 允许 | 允许 | | **regular** | 支持 | 支持 | 支持 | 支持 | 不支持 | 不支持 | 支持 |
| @Link | 不允许 | 允许 | 不推荐 | 允许 | | **@State** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| @Prop | 不允许 | 不允许 | 允许 | 允许 | | **@Link** | 不支持 | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) |
| @StorageLink | 不允许 | 允许 | 不允许 | 不允许 | | **@Prop** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| @StorageProp | 不允许 | 不允许 | 不允许 | 允许 | | **@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的强类型规则。 - 除了上述规则外,还需要遵循TS的强类型规则。
\ No newline at end of file
示例:
```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框架会针 ...@@ -30,3 +30,5 @@ AppStorage是整个应用程序状态的中心“数据库”,UI框架会针
- @LocalStorageProp:组件通过使用@LocalStorageProp(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立单向数据绑定。 - @LocalStorageProp:组件通过使用@LocalStorageProp(key)装饰的状态变量,key值为LocalStorage中的属性键值,与LocalStorage建立单向数据绑定。
- PersistentStorage提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。 - PersistentStorage提供了一些静态方法用来管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据,或者通过@StorageLink装饰器来访问对应key的变量。
- Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态数据,这些数据描述了应用程序运行的设备环境。 - Environment是框架在应用程序启动时创建的单例对象,它为AppStorage提供了一系列应用程序需要的环境状态数据,这些数据描述了应用程序运行的设备环境。
请参考[状态变量数据类型声明的使用限制](arkts-restrictions-and-extensions.md)了解状态变量使用规范。
...@@ -261,22 +261,22 @@ ...@@ -261,22 +261,22 @@
- 订阅者所需权限: 无 - 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN
(预留事件,暂未支持)表示分布式号登录成功的动作。 (预留事件,暂未支持)表示分布式号登录成功的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGIN - 值: usual.event.DISTRIBUTED_ACCOUNT_LOGIN
- 订阅者所需权限: 无 - 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT
(预留事件,暂未支持)表示分布式号登出成功的动作。 (预留事件,暂未支持)表示分布式号登出成功的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOUT - 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOUT
- 订阅者所需权限: 无 - 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID
(预留事件,暂未支持)表示分布式号token令牌无效的动作。 (预留事件,暂未支持)表示分布式号token令牌无效的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID - 值: usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID
- 订阅者所需权限: 无 - 订阅者所需权限: 无
## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF ## COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF
(预留事件,暂未支持)表示分布式号注销的动作。 (预留事件,暂未支持)表示分布式号注销的动作。
- 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOFF - 值: usual.event.DISTRIBUTED_ACCOUNT_LOGOFF
- 订阅者所需权限: 无 - 订阅者所需权限: 无
......
...@@ -239,7 +239,7 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, ...@@ -239,7 +239,7 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions,
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ----------------------- | | -------- | --------------------- | ---- | ----------------------- |
| owner | string | 是 | 应用帐号所有者的包名。 | | owner | string | 是 | 应用帐号所有者的包名。 |
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 | | options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 |
| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,返回创建结果。 | | callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,返回创建结果。 |
**错误码:** **错误码:**
...@@ -2802,7 +2802,7 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;) ...@@ -2802,7 +2802,7 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;)
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------- | ---- | ---------------------------------------- | | --------- | ------------------------- | ---- | ---------------------------------------- |
| name | string | 是 | 应用帐号的名称。 | | name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 | | extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当创建成功时,err为null,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当创建成功时,err为null,否则为错误对象。 |
**示例:** **示例:**
...@@ -2830,7 +2830,7 @@ addAccount(name: string, extraInfo?: string): Promise&lt;void&gt; ...@@ -2830,7 +2830,7 @@ addAccount(name: string, extraInfo?: string): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ---------------------------------------- | | --------- | ------ | ---- | ---------------------------------------- |
| name | string | 是 | 应用帐号的名称。 | | name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 否 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 | | extraInfo | string | 否 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
**返回值:** **返回值:**
...@@ -3239,7 +3239,7 @@ setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback&lt; ...@@ -3239,7 +3239,7 @@ setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback&lt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------------- | ---- | --------------- | | --------- | ------------------------- | ---- | --------------- |
| name | string | 是 | 应用帐号的名称。 | | name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 | | extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当设置成功时,err为null,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当设置成功时,err为null,否则为错误对象。 |
**示例:** **示例:**
...@@ -3269,7 +3269,7 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise&lt;void&gt; ...@@ -3269,7 +3269,7 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | --------- | | --------- | ------ | ---- | --------- |
| name | string | 是 | 应用帐号的名称。 | | name | string | 是 | 应用帐号的名称。 |
| extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 | | extraInfo | string | 是 | 额外信息(能转换string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用号密码、token等)。 |
**返回值:** **返回值:**
...@@ -4558,7 +4558,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt; ...@@ -4558,7 +4558,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
## CreateAccountOptions<sup>9+</sup> ## CreateAccountOptions<sup>9+</sup>
表示创建号的选项。 表示创建号的选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。
...@@ -4568,7 +4568,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt; ...@@ -4568,7 +4568,7 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
## CreateAccountImplicitlyOptions<sup>9+</sup> ## CreateAccountImplicitlyOptions<sup>9+</sup>
表示隐式创建号的选项。 表示隐式创建号的选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Account.AppAccount。
...@@ -4878,7 +4878,7 @@ createAccountImplicitly(options: CreateAccountImplicitlyOptions, callback: AuthC ...@@ -4878,7 +4878,7 @@ createAccountImplicitly(options: CreateAccountImplicitlyOptions, callback: AuthC
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 | | options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建号的选项。 |
| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,用于返回创建结果。 | | callback | [AuthCallback](#authcallback9) | 是 | 认证器回调对象,用于返回创建结果。 |
### addAccountImplicitly<sup>(deprecated)</sup> ### addAccountImplicitly<sup>(deprecated)</sup>
......
...@@ -12,9 +12,9 @@ import camera from '@ohos.multimedia.camera'; ...@@ -12,9 +12,9 @@ import camera from '@ohos.multimedia.camera';
## camera.getCameraManager ## camera.getCameraManager
getCameraManager(context: Context, callback: AsyncCallback<CameraManager\>): void getCameraManager(context: Context): CameraManager
获取相机管理器实例,通过注册回调函数获取结果。 获取相机管理器实例,同步返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -23,46 +23,17 @@ getCameraManager(context: Context, callback: AsyncCallback<CameraManager\>): voi ...@@ -23,46 +23,17 @@ getCameraManager(context: Context, callback: AsyncCallback<CameraManager\>): voi
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------- | ---- | ---------------------------- | | -------- | ----------------------------------------------- | ---- | ---------------------------- |
| context | [Context](js-apis-inner-app-context.md) | 是 | 应用上下文。 | | context | [Context](js-apis-inner-app-context.md) | 是 | 应用上下文。 |
| callback | AsyncCallback<[CameraManager](#cameramanager)\> | 是 | 回调函数,用于获取相机管理器实例。 |
**示例:**
```js
camera.getCameraManager(context, (err, cameraManager) => {
if (err) {
console.error(`Failed to get the CameraManager instance ${err.message}`);
return;
}
console.log('Callback returned with the CameraManager instance');
});
```
## camera.getCameraManager
getCameraManager(context: Context): Promise<CameraManager\>
获取相机管理器实例,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | ------------ |
| context | [Context](js-apis-inner-app-context.md) | 是 | 应用上下文。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------------------------------- | ----------------------------------- | | ----------------------------------------------- | ---------------------------- |
| Promise<[CameraManager](#cameramanager)\> | 使用Promise的方式获取一个相机管理器实例。 | | [CameraManager](#cameramanager) | 相机管理器。 |
**示例:** **示例:**
```js ```js
camera.getCameraManager(context).then((cameraManager) => { let cameraManager = camera.getCameraManager(context);
console.log('Promise returned with the CameraManager instance.');
})
``` ```
## CameraStatus ## CameraStatus
...@@ -71,12 +42,12 @@ camera.getCameraManager(context).then((cameraManager) => { ...@@ -71,12 +42,12 @@ camera.getCameraManager(context).then((cameraManager) => {
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ------------------------- | ---- | ------------ | | ------------------------- | ---- | ------------ |
| CAMERA_STATUS_APPEAR | 0 | 新的相机出现。 | | CAMERA_STATUS_APPEAR | 0 | 新的相机出现。 |
| CAMERA_STATUS_DISAPPEAR | 1 | 相机被移除。 | | CAMERA_STATUS_DISAPPEAR | 1 | 相机被移除。 |
| CAMERA_STATUS_AVAILABLE | 2 | 相机可用。 | | CAMERA_STATUS_AVAILABLE | 2 | 相机可用。 |
| CAMERA_STATUS_UNAVAILABLE | 3 | 相机不可用。 | | CAMERA_STATUS_UNAVAILABLE | 3 | 相机不可用。 |
## Profile ## Profile
...@@ -123,64 +94,54 @@ camera.getCameraManager(context).then((cameraManager) => { ...@@ -123,64 +94,54 @@ camera.getCameraManager(context).then((cameraManager) => {
| videoProfiles | Array<[VideoProfile](#videoprofile)\> | 是 | 支持的录像配置信息。 | | videoProfiles | Array<[VideoProfile](#videoprofile)\> | 是 | 支持的录像配置信息。 |
| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | 支持的metadata流类型信息。| | supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | 支持的metadata流类型信息。|
## CameraManager ## CameraErrorCode
相机管理器类,使用前需要通过getCameraManager获取相机管理实例。
### getSupportedCameras
getSupportedCameras(callback: AsyncCallback<Array<CameraDevice\>\>): void
获取支持指定的相机设备对象,通过注册回调函数获取结果 相机错误码。接口使用不正确以及on接口监听error状态返回
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:** | 名称 | 值 | 说明 |
| ------------------------- | ---- | ------------ |
| 参数名 | 类型 | 必填 | 说明 | | INVALID_ARGUMENT | 7400101 | 参数缺失或者参数类型不对。 |
| -------- | ----------------------------------------------------- | ---- | ------------------------------- | | OPERATION_NOT_ALLOWED | 7400102 | 操作流程不对,不允许。 |
| callback | AsyncCallback<Array<[CameraDevice](#cameradevice)\>\> | 是 | 使用callback方式获取支持的相机列表。 | | SESSION_NOT_CONFIG | 7400103 | session 未配置返回。 |
| SESSION_NOT_RUNNING | 7400104 | session 未运行返回。 |
| SESSION_CONFIG_LOCKED | 7400105 | session 配置已锁定返回。 |
| DEVICE_SETTING_LOCKED | 7400106 | 设备设置已锁定返回。 |
| CONFILICT_CAMERA | 7400107 | 设备重复打开返回。 |
| DEVICE_DISABLED | 7400108 | 安全原因摄像头被禁用。 |
| SERVICE_FATAL_ERROR | 7400201 | 相机服务错误返回。 |
**示例:** ## CameraManager
```js 相机管理器类,使用前需要通过getCameraManager获取相机管理实例。
cameraManager.getSupportedCameras((err, cameras) => {
if (err) {
console.error(`Failed to get the cameras. ${err.message}`);
return;
}
console.log(`Callback returned with an array of supported cameras: ${cameras.length}`);
})
```
### getSupportedCameras ### getSupportedCameras
getSupportedCameras(): Promise<Array<CameraDevice\>\> getSupportedCameras(): Array<CameraDevice\>
获取支持指定的相机设备对象,通过Promise获取结果。 获取支持指定的相机设备对象,同步返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------------------------------------- | ------------------------- | | ----------------------------------------------- | ---------------------------- |
| Promise<Array<[CameraDevice](#cameradevice)\>\> | 使用promise获取支持相机列表。 | | Array<[CameraDevice](#cameradevice)> | 相机设备列表。 |
**示例:** **示例:**
```js ```js
cameraManager.getSupportedCameras().then((cameras) => { let cameras = cameraManager.getSupportedCameras();
console.log(`Promise returned with an array of supported cameras: ${cameras.length}`);
})
``` ```
### getSupportedOutputCapability ### getSupportedOutputCapability
getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback<CameraOutputCapability\>): void getSupportedOutputCapability(cameraDevice:CameraDevice): CameraOutputCapability
查询相机设备在模式下支持的输出能力,通过注册回调函数获取结果。 查询相机设备在模式下支持的输出能力,同步返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -189,52 +150,19 @@ getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback<Camera ...@@ -189,52 +150,19 @@ getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback<Camera
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------------ |--------------------------------------------------------------- | -- | -------------------------- | | ------------ |--------------------------------------------------------------- | -- | -------------------------- |
| cameraDevice | [CameraDevice](#cameradevice) | 是 | 相机设备,通过 getSupportedCameras 接口获取 | | cameraDevice | [CameraDevice](#cameradevice) | 是 | 相机设备,通过 getSupportedCameras 接口获取 |
| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | 是 | 使用callback方式获取相机输出能力。 |
**示例:**
```js
cameraManager.getSupportedCameras().then((cameras) => {
let cameraDevice = cameras[0];
cameraManager.getSupportedOutputCapability(cameraDevice, (err, CameraOutputCapability) => {
if (err) {
console.error(`Failed to get the outputCapability. ${err.message}`);
return;
}
console.log('Callback returned with an array of supported outputCapability');
})
})
```
### getSupportedOutputCapability
getSupportedOutputCapability(camera:CameraDevice): Promise<CameraOutputCapability\>
查询相机设备在模式下支持的输出能力,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------- | ---- | ---------- |
| cameradevice | [CameraDevice](#cameradevice) | 是 | 相机设备,通过 getSupportedCameras 接口获取 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------------------------------------------------------- | ----------------------------- | | ----------------------------------------------- | ---------------------------- |
| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | 使用Promise的方式获取结果,返回相机输出能力。 | | [CameraOutputCapability](#cameraoutputcapability) | 相机输出能力。 |
**示例:** **示例:**
```js ```js
cameraManager.getSupportedCameras().then((cameras) => { let cameraDevice = cameras[0];
let cameraDevice = cameras[0]; let cameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevice);
cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapability) => {
console.log('Promise returned with an array of supported outputCapability');
})
})
``` ```
### isCameraMuted ### isCameraMuted
...@@ -306,9 +234,9 @@ cameraManager.muteCamera(mute); ...@@ -306,9 +234,9 @@ cameraManager.muteCamera(mute);
### createCameraInput ### createCameraInput
createCameraInput(camera: CameraDevice, callback: AsyncCallback<CameraInput\>): void createCameraInput(camera: CameraDevice): CameraInput
使用CameraDevice对象异步创建CameraInput实例,通过注册回调函数获取结果。 使用CameraDevice对象创建CameraInput实例,同步返回结果。
**需要权限:** ohos.permission.CAMERA **需要权限:** ohos.permission.CAMERA
...@@ -318,58 +246,32 @@ createCameraInput(camera: CameraDevice, callback: AsyncCallback<CameraInput\>): ...@@ -318,58 +246,32 @@ createCameraInput(camera: CameraDevice, callback: AsyncCallback<CameraInput\>):
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------- | ---- | --------------------------------- | | -------- | ------------------------------------------- | ---- | --------------------------------- |
| cameraDevice | [CameraDevice](#cameradevice) | 是 | CameraDevice对象,通过 getSupportedCameras 接口获取 | | cameraDevice | [CameraDevice](#cameradevice) | 是 | CameraDevice对象,通过 getSupportedCameras 接口获取 |
| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 |
**示例:**
```js
let cameraDevice = cameras[0];
cameraManager.createCameraInput(cameraDevice, (err, cameraInput) => {
if (err) {
console.error(`Failed to create the CameraInput instance. ${err.message}`);
return;
}
console.log('Callback returned with the CameraInput instance.');
})
```
### createCameraInput
createCameraInput(cameraDevice: CameraDevice): Promise<CameraInput\>
使用CameraDevice对象异步创建CameraInput实例,通过Promise获取结果。
**需要权限:** ohos.permission.CAMERA
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------- | ---- | ---------- |
| cameraDevice | [CameraDevice](#cameradevice) | 是 | CameraDevice对象,通过 getSupportedCameras 接口获取 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------- | ------------------------------------ | | ---------- | ----------------------------- |
| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | | [CameraInput](#camerainput) | CameraInput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
let cameraDevice = cameras[0]; let cameraDevice = cameras[0];
cameraManager.createCameraInput(cameraDevice).then((cameraInput) => { let cameraInput;
console.log('Promise returned with the CameraInput instance'); try {
}) cameraInput = cameraManager.createCameraInput(cameraDevice);
} catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### createCameraInput ### createCameraInput
createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback<CameraInput\>): void createCameraInput(position: CameraPosition, type: CameraType): CameraInput
根据相机位置和类型创建CameraInput实例,通过注册回调函数获取结果。 根据相机位置和类型创建CameraInput实例,同步返回结果。
**需要权限:** ohos.permission.CAMERA **需要权限:** ohos.permission.CAMERA
...@@ -381,45 +283,12 @@ createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCal ...@@ -381,45 +283,12 @@ createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCal
| -------- | ------------------------------------------- | ---- | --------------------------------- | | -------- | ------------------------------------------- | ---- | --------------------------------- |
| position | [CameraPosition](#cameraposition) | 是 | 相机位置,通过 getSupportedCameras 接口获取设备,然后获取设备位置信息 | | position | [CameraPosition](#cameraposition) | 是 | 相机位置,通过 getSupportedCameras 接口获取设备,然后获取设备位置信息 |
| type | [CameraType](#cameratype) | 是 | 相机类型,通过 getSupportedCameras 接口获取设备,然后获取设备类型信息 | | type | [CameraType](#cameratype) | 是 | 相机类型,通过 getSupportedCameras 接口获取设备,然后获取设备类型信息 |
| callback | AsyncCallback<[CameraInput](#camerainput)\> | 是 | 回调函数,用于获取CameraInput实例。 |
**示例:**
```js
let cameraDevice = cameras[0];
let position = cameraDevice.cameraPosition;
let type = cameraDevice.cameraType;
cameraManager.createCameraInput(position, type, (err, cameraInput) => {
if (err) {
console.error(`Failed to create the CameraInput instance. ${err.message}`);
return;
}
console.log('Callback returned with the CameraInput instance');
})
```
### createCameraInput
createCameraInput(position: CameraPosition, type:CameraType ): Promise<CameraInput\>
根据相机位置和类型创建CameraInput实例,通过Promise获取结果。
**需要权限:** ohos.permission.CAMERA
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------- | ---- | ------------ |
| position | [CameraPosition](#cameraposition) | 是 | 相机位置,通过 getSupportedCameras 接口获取设备,然后获取设备位置信息 |
| type | [CameraType](#cameratype) | 是 | 相机类型,通过 getSupportedCameras 接口获取设备,然后获取设备类型信息 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------- | ------------------------------------ | | ---------- | ----------------------------- |
| Promise<[CameraInput](#camerainput)\> | 使用Promise的方式获取CameraInput的实例。 | | [CameraInput](#camerainput) | CameraInput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
...@@ -427,16 +296,20 @@ createCameraInput(position: CameraPosition, type:CameraType ): Promise<CameraInp ...@@ -427,16 +296,20 @@ createCameraInput(position: CameraPosition, type:CameraType ): Promise<CameraInp
let cameraDevice = cameras[0]; let cameraDevice = cameras[0];
let position = cameraDevice.cameraPosition; let position = cameraDevice.cameraPosition;
let type = cameraDevice.cameraType; let type = cameraDevice.cameraType;
cameraManager.createCameraInput(position, type).then((cameraInput) => { let cameraInput;
console.log('Promise returned with the CameraInput instance'); try {
}) cameraInput = cameraManager.createCameraInput(position, type);
} catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### createPreviewOutput ### createPreviewOutput
createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PreviewOutput\>): void createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput
创建预览输出对象,通过注册回调函数获取结果。 创建预览输出对象,同步返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -446,56 +319,31 @@ createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback ...@@ -446,56 +319,31 @@ createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback
| -------- | ----------------------------------------------- | ---- | ------------------------------- | | -------- | ----------------------------------------------- | ---- | ------------------------------- |
| profile | [Profile](#profile) | 是 | 支持的预览配置信息,通过getSupportedOutputCapability接口获取。| | profile | [Profile](#profile) | 是 | 支持的预览配置信息,通过getSupportedOutputCapability接口获取。|
| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)或者[ImageReceiver](js-apis-image.md#imagereceiver9)组件获取的surfaceId。| | surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)或者[ImageReceiver](js-apis-image.md#imagereceiver9)组件获取的surfaceId。|
| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。|
**示例:**
```js
let profile = cameraoutputcapability.previewProfiles[0];
cameraManager.createPreviewOutput(profile, surfaceId, (err, previewOutput) => {
if (err) {
console.error(`Failed to gcreate previewOutput. ${err.message}`);
return;
}
console.log('Callback returned with previewOutput created.');
})
```
### createPreviewOutput
createPreviewOutput(profile: Profile, surfaceId: string): Promise<PreviewOutput\>
创建预览输出对象,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------| ---- | ----------------- |
| profile | [Profile](#profile) | 是 | 支持的预览配置信息,通过getSupportedOutputCapability接口获取。|
| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)或者[ImageReceiver](js-apis-image.md#imagereceiver9)组件获取的surfaceId。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ---------------------------------------- | ---------------------------------------- | | ---------- | ----------------------------- |
| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取PreviewOutput的实例。 | | [PreviewOutput](#previewoutput) | PreviewOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
let profile = cameraoutputcapability.previewProfiles[0]; let profile = cameraoutputcapability.previewProfiles[0];
cameraManager.createPreviewOutput(profile, surfaceId).then((previewOutput) => { let previewOutput;
console.log('Promise returned with previewOutput created.'); try {
}) previewOutput = cameraManager.createPreviewOutput(profile, surfaceId);
} catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### createPhotoOutput ### createPhotoOutput
createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PhotoOutput\>): void createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput
创建拍照输出对象,通过注册回调函数获取结果。 创建拍照输出对象,同步返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -505,56 +353,31 @@ createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<P ...@@ -505,56 +353,31 @@ createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<P
| -------- | ------------------------------------------- | ---- | ----------------------------------- | | -------- | ------------------------------------------- | ---- | ----------------------------------- |
| profile | [Profile](#profile) | 是 | 支持的拍照配置信息,通过getSupportedOutputCapability接口获取。| | profile | [Profile](#profile) | 是 | 支持的拍照配置信息,通过getSupportedOutputCapability接口获取。|
| surfaceId| string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的surfaceId。| | surfaceId| string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的surfaceId。|
| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | 是 | 回调函数,用于获取PhotoOutput实例。 |
**示例:**
```js
let profile = cameraoutputcapability.photoProfiles[0];
cameraManager.createPhotoOutput(profile, surfaceId, (err, photoOutput) => {
if (err) {
console.error(`Failed to create photoOutput. ${err.message}`);
return;
}
console.log('Callback returned with photoOutput created.');
})
```
### createPhotoOutput
createPhotoOutput(profile: Profile, surfaceId: string): Promise<PhotoOutput\>
创建拍照输出对象,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------| ---- | ----------- |
| profile | [Profile](#profile) | 是 | 支持的拍照配置信息,通过getSupportedOutputCapability接口获取。 |
| surfaceId| string | 是 | 从[ImageReceiver](js-apis-image.md#imagereceiver9)获取的surfaceId。|
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------- | -------------------------------------- | | ---------- | ----------------------------- |
| Promise<[PhotoOutput](#photooutput)\> | 使用Promise的方式获取PhotoOutput的实例。 | | [PhotoOutput](#photooutput) | PhotoOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
let profile = cameraoutputcapability.photoProfiles[0]; let profile = cameraoutputcapability.photoProfiles[0];
cameraManager.createPhotoOutput(profile, surfaceId).then((photoOutput) => { let photoOutput;
console.log('Promise returned with photoOutput created.'); try {
}) photoOutput = cameraManager.createPhotoOutput(profile, surfaceId);
} catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### createVideoOutput ### createVideoOutput
createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback<VideoOutput\>): void createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput
创建录像输出对象,通过注册回调函数获取结果。 创建录像输出对象,同步返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -564,56 +387,31 @@ createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallb ...@@ -564,56 +387,31 @@ createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallb
| -------- | ------------------------------------------- | ---- | ------------------------------ | | -------- | ------------------------------------------- | ---- | ------------------------------ |
| profile | [VideoProfile](#videoprofile) | 是 | 支持的录像配置信息,通过getSupportedOutputCapability接口获取。 | | profile | [VideoProfile](#videoprofile) | 是 | 支持的录像配置信息,通过getSupportedOutputCapability接口获取。 |
| surfaceId| string | 是 | 从[VideoRecorder](js-apis-media.md#videorecorder9)获取的surfaceId。| | surfaceId| string | 是 | 从[VideoRecorder](js-apis-media.md#videorecorder9)获取的surfaceId。|
| callback | AsyncCallback<[VideoOutput](#videooutput)\> | 是 | 回调函数,用于获取VideoOutput实例。 |
**示例:**
```js
let profile = cameraoutputcapability.videoProfiles[0];
cameraManager.createVideoOutput(profile, surfaceId, (err, videoOutput) => {
if (err) {
console.error(`Failed to create videoOutput. ${err.message}`);
return;
}
console.log('Callback returned with an array of supported outputCapability' );
})
```
### createVideoOutput
createVideoOutput(profile: VideoProfile, surfaceId: string): Promise<VideoOutput\>
创建录像输出对象,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------| ---- | ---------- |
| profile | [VideoProfile](#videoprofile) | 是 | 支持的录像配置信息,通过getSupportedOutputCapability接口获取。 |
| surfaceId| string | 是 | 从[VideoRecorder](js-apis-media.md#videorecorder9)获取的surfaceId。|
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------- | -------------------------------------- | | ---------- | ----------------------------- |
| Promise<[VideoOutput](#videooutput)\> | 使用Promise的方式获取videoOutput的实例。 | | [VideoOutput](#videooutput) | VideoOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
let profile = cameraoutputcapability.videoProfiles[0]; let profile = cameraoutputcapability.videoProfiles[0];
cameraManager.createVideoOutput(profile, surfaceId).then((videoOutput) => { let videoOutput;
console.log('Promise returned with videoOutput created.'); try {
}) videoOutput = cameraManager.createVideoOutput(profile, surfaceId);
} catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### createMetadataOutput ### createMetadataOutput
createMetadataOutput(metadataObjectTypes:Array<MetadataObjectType\>, callback: AsyncCallback<MetadataOutput\>): void createMetadataOutput(metadataObjectTypes:Array<MetadataObjectType\>): MetadataOutput
创建metadata流输出对象,通过注册回调函数获取结果。 创建metadata流输出对象,同步返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -622,103 +420,57 @@ createMetadataOutput(metadataObjectTypes:Array<MetadataObjectType\>, callback: A ...@@ -622,103 +420,57 @@ createMetadataOutput(metadataObjectTypes:Array<MetadataObjectType\>, callback: A
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------------------- | -------------------------------------------------- | --- | ---------------------------- | | -------------------- | -------------------------------------------------- | --- | ---------------------------- |
| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型信息,通过getSupportedOutputCapability接口获取。 | | metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型信息,通过getSupportedOutputCapability接口获取。 |
| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | 是 | 回调函数,用于获取MetadataOutput实例。 |
**示例:**
```js
let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes;
cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataOutput) => {
if (err) {
console.error(`Failed to create metadataOutput. ${err.message}`);
return;
}
console.log('Callback returned with metadataOutput created.');
})
```
### createMetadataOutput
createMetadataOutput(metadataObjectTypes:Array<MetadataObjectType\>): Promise<MetadataOutput\>
创建metadata流输出对象,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------------------- | -------------------------------------------------- | --- | -------------------- |
| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型信息,通过getSupportedOutputCapability接口获取。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------------ | ----------------------------------------- | | ---------- | ----------------------------- |
| Promise<[MetadataOutput](#metadataoutput)\> | 使用Promise的方式获取MetadataOutput的实例。 | | [MetadataOutput](#metadataoutput) | MetadataOutput实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes; let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes;
cameraManager.createMetadataOutput(metadataObjectTypes).then((metadataOutput) => { let metadataOutput;
console.log('Promise returned with metadataOutput created.'); try {
}) metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes);
} catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### createCaptureSession ### createCaptureSession
createCaptureSession(callback: AsyncCallback<CaptureSession\>): void createCaptureSession(): CaptureSession
创建CaptureSession实例,通过注册回调函数获取结果。 创建CaptureSession实例,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------------------- | ----------------------------------------- | ----------- | ---------------------------- |
| callback | AsyncCallback<[CaptureSession](#capturesession)\> | 是 | 回调函数,用于获取拍照会话实例。 |
**示例:**
```js
cameraManager.createCaptureSession((err, captureSession) => {
if (err) {
console.error(`Failed to create captureSession. ${err.message}`);
return;
}
console.log('Callback returned with captureSession created.');
})
```
### createCaptureSession
createCaptureSession(): Promise<CaptureSession\>
创建CaptureSession实例,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------------------- | ---------------------------------------- | | ---------- | ----------------------------- |
| Promise<[CaptureSession](#capturesession)\> | 使用Promise的方式获取CaptureSession的实例。 | | [CaptureSession](#capturesession) | CaptureSession实例。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
cameraManager.createCaptureSession().then((captureSession) => { let captureSession;
console.log('Promise returned with captureSession created.'); try {
}) captureSession = cameraManager.createCaptureSession();
} catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### on('cameraStatus') ### on('cameraStatus')
on(type: 'cameraStatus', callback: AsyncCallback<CameraStatusInfo\>): void on(type: 'cameraStatus', callback: AsyncCallback<CameraStatusInfo\>): void
镜头状态回调,通过注册回调函数获取相机的状态变化。 相机设备状态回调,通过注册回调函数获取相机的状态变化。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -726,17 +478,13 @@ on(type: 'cameraStatus', callback: AsyncCallback<CameraStatusInfo\>): void ...@@ -726,17 +478,13 @@ on(type: 'cameraStatus', callback: AsyncCallback<CameraStatusInfo\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------- | ---- | --------- | | -------- | ----------------------------------------------------- | ---- | --------- |
| type | string | 是 | 监听事件,固定为'cameraStatus',即镜头状态变化事件。 | | type | string | 是 | 监听事件,固定为'cameraStatus',callback返回相机设备信息,包含设备以及设备对应的状态(可用、不可用等),cameraManager对象获取成功可监听。 |
| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取镜头状态变化信息。 | | callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | 是 | 回调函数,用于获取镜头状态变化信息。 |
**示例:** **示例:**
```js ```js
cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { cameraManager.on('cameraStatus', (cameraStatusInfo) => {
if (err) {
console.error(`Failed to get cameraStatus callback. ${err.message}`);
return;
}
console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); console.log(`camera : ${cameraStatusInfo.camera.cameraId}`);
console.log(`status: ${cameraStatusInfo.status}`); console.log(`status: ${cameraStatusInfo.status}`);
}) })
...@@ -756,17 +504,14 @@ on(type: 'cameraMute', callback: AsyncCallback<boolean\>): void ...@@ -756,17 +504,14 @@ on(type: 'cameraMute', callback: AsyncCallback<boolean\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------- | ---- | --------- | | -------- | --------------- | ---- | --------- |
| type | string | 是 | 监听事件,固定为'cameraMute',即禁用状态变化事件。 | | type | string | 是 | 监听事件,固定为'cameraMute',系统相机摄像头开关,callback返回开关状态变化信息,cameraManager对象获取成功可监听。 |
| callback | AsyncCallback\<boolean> | 是 | 回调函数,用于获取禁用状态变化信息。 | | callback | AsyncCallback\<boolean> | 是 | 回调函数,用于获取禁用状态变化信息。 |
**示例:** **示例:**
```js ```js
cameraManager.on('cameraMute', (err, curMuetd) => { cameraManager.on('cameraMute', (curMuetd) => {
if (err) { let isMuted = curMuetd;
console.error(`Failed to get cameraMute callback. ${err.message}`);
return;
}
}) })
``` ```
...@@ -801,7 +546,7 @@ cameraManager.on('cameraMute', (err, curMuetd) => { ...@@ -801,7 +546,7 @@ cameraManager.on('cameraMute', (err, curMuetd) => {
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ----------------------- | ---- | -------------- | | ----------------------- | ---- | -------------- |
| CAMERA_TYPE_UNSPECIFIED | 0 | 相机类型未指定。 | | CAMERA_TYPE_DEFAULT | 0 | 相机类型未指定。 |
| CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。 | | CAMERA_TYPE_WIDE_ANGLE | 1 | 广角相机。 |
| CAMERA_TYPE_ULTRA_WIDE | 2 | 超广角相机。 | | CAMERA_TYPE_ULTRA_WIDE | 2 | 超广角相机。 |
| CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。 | | CAMERA_TYPE_TELEPHOTO | 3 | 长焦相机。 |
...@@ -882,14 +627,14 @@ open\(callback: AsyncCallback<void\>\): void ...@@ -882,14 +627,14 @@ open\(callback: AsyncCallback<void\>\): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
cameraInput.open((err) => { cameraInput.open((err) => {
if (err) { if (err) {
console.error(`Failed to open the camera. ${err.message}`); console.error(`Failed to open the camera. ${err.code}`);
return; return;
} }
console.log('Callback returned with camera opened.'); console.log('Callback returned with camera opened.');
...@@ -908,14 +653,16 @@ open(): Promise<void\> ...@@ -908,14 +653,16 @@ open(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
cameraInput.open().then(() => { cameraInput.open().then(() => {
console.log('Promise returned with camera opened.'); console.log('Promise returned with camera opened.');
}) }).catch((err) => {
console.error(`Failed to open the camera. ${err.code}`);
});
``` ```
### close ### close
...@@ -930,14 +677,14 @@ close\(callback: AsyncCallback<void\>\): void ...@@ -930,14 +677,14 @@ close\(callback: AsyncCallback<void\>\): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
cameraInput.close((err) => { cameraInput.close((err) => {
if (err) { if (err) {
console.error(`Failed to close the cameras. ${err.message}`); console.error(`Failed to close the cameras. ${err.code}`);
return; return;
} }
console.log('Callback returned with camera closed.'); console.log('Callback returned with camera closed.');
...@@ -963,109 +710,37 @@ close(): Promise<void\> ...@@ -963,109 +710,37 @@ close(): Promise<void\>
```js ```js
cameraInput.close().then(() => { cameraInput.close().then(() => {
console.log('Promise returned with camera closed.'); console.log('Promise returned with camera closed.');
}) }).catch((err) => {
console.error(`Failed to close the cameras. ${err.code}`);
});
``` ```
### release ### on('error')
release\(callback: AsyncCallback<void\>\): void on(type: 'error', cameraDevice:CameraDevice, callback: ErrorCallback<BusinessError\>): void
释放资源,通过注册回调函数获取结果。 监听CameraInput的错误事件,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------------------- | --- | ------------------------------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | type | string | 是 | 监听事件,固定为'error',callback返回错误码,比如(设备不可用或者冲突等返回对应错误码),CameraInput对象创建成功可监听。 |
| cameraDevice | [CameraDevice](#cameradevice) | 是 | CameraDevice对象。 |
| callback | ErrorCallback<BusinessError\> | 是 | 回调函数,用于获取结果。返回错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
cameraInput.release((err) => { let cameraDevice = cameras[0];
if (err) { cameraInput.on('error', cameraDevice, (error) => {
console.error(`Failed to release the CameraInput instance ${err.message}`); console.log(`Camera input error code: ${error.code}`);
return; })
}
console.log('Callback invoked to indicate that the CameraInput instance is released successfully.');
});
``` ```
### release ## FlashMode
release(): Promise<void\>
释放资源,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:**
| 类型 | 说明 |
| -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 |
**示例:**
```js
cameraInput.release().then(() => {
console.log('Promise returned to indicate that the CameraInput instance is released successfully.');
})
```
### on('error')
on(type: 'error', cameraDevice:CameraDevice, callback: ErrorCallback<CameraInputError\>): void
监听CameraInput的错误事件,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------- | --- | ------------------------------------------- |
| type | string | 是 | 监听事件,固定为'error',即CameraInput错误事件。 |
| cameraDevice | [CameraDevice](#cameradevice) | 是 | CameraDevice对象。 |
| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
let cameraDevice = cameras[0];
cameraInput.on('error', cameraDevice, (cameraInputError) => {
console.log(`Camera input error code: ${cameraInputError.code}`);
})
```
## CameraInputErrorCode
枚举,[CameraInput](#camerainput)错误类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 |
| ------------------------- | ---- | ---------- |
| ERROR_UNKNOWN | -1 | 未知错误。 |
| ERROR_NO_PERMISSION | 0 | 没有权限。 |
| ERROR_DEVICE_PREEMPTED | 1 | 相机被抢占。 |
| ERROR_DEVICE_DISCONNECTED | 2 | 相机断开连接。 |
| ERROR_DEVICE_IN_USE | 3 | 相机正在使用。 |
| ERROR_DRIVER_ERROR | 4 | 驱动错误。 |
## CameraInputError
[CameraInput](#camerainput)错误码。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 类型 | 必填 | 说明 |
| ---- | --------------------------------------------- | ------------ |--------------------- |
| code | [CameraInputErrorCode](#camerainputerrorcode) | 是 |CameraInput中的错误码。 |
## FlashMode
枚举,闪光灯模式。 枚举,闪光灯模式。
...@@ -1135,56 +810,32 @@ cameraInput.on('error', cameraDevice, (cameraInputError) => { ...@@ -1135,56 +810,32 @@ cameraInput.on('error', cameraDevice, (cameraInputError) => {
### beginConfig ### beginConfig
beginConfig\(callback: AsyncCallback<void\>\): void beginConfig(): void
开始配置会话,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
captureSession.beginConfig((err) => {
if (err) {
console.error(`Failed to start the configuration. ${err.message}`);
return;
}
console.log('Callback invoked to indicate the begin config success.');
});
```
### beginConfig
beginConfig\(\): Promise<void\>
开始配置会话,通过Promise获取结果 开始配置会话。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------ | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.beginConfig().then(() => { try {
console.log('Promise returned to indicate the begin config success.'); captureSession.beginConfig();
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### commitConfig ### commitConfig
commitConfig\(callback: AsyncCallback<void\>\): void commitConfig(callback: AsyncCallback<void\>): void
提交配置信息,通过注册回调函数获取结果。 提交配置信息,通过注册回调函数获取结果。
...@@ -1194,14 +845,14 @@ commitConfig\(callback: AsyncCallback<void\>\): void ...@@ -1194,14 +845,14 @@ commitConfig\(callback: AsyncCallback<void\>\): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.commitConfig((err) => { captureSession.commitConfig((err) => {
if (err) { if (err) {
console.error(`Failed to commit the configuration. ${err.message}`); console.log('Failed to commitConfig '+ err.code);
return; return;
} }
console.log('Callback invoked to indicate the commit config success.'); console.log('Callback invoked to indicate the commit config success.');
...@@ -1210,7 +861,7 @@ captureSession.commitConfig((err) => { ...@@ -1210,7 +861,7 @@ captureSession.commitConfig((err) => {
### commitConfig ### commitConfig
commitConfig\(\): Promise<void\> commitConfig(): Promise<void\>
提交配置信息,通过Promise获取结果。 提交配置信息,通过Promise获取结果。
...@@ -1220,48 +871,24 @@ commitConfig\(\): Promise<void\> ...@@ -1220,48 +871,24 @@ commitConfig\(\): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.commitConfig().then(() => { captureSession.commitConfig().then(() => {
console.log('Promise returned to indicate the commit config success.'); console.log('Promise returned to indicate the commit config success.');
}) }).catch((err) => {
``` // 失败返回错误码error.code并处理
console.log('Failed to commitConfig '+ err.code);
### addInput
addInput\(cameraInput: CameraInput, callback: AsyncCallback<void\>\): void
[CameraInput](#camerainput)加入到会话,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | --------------------------- | ---- | ------------------------ |
| cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
captureSession.addInput(cameraInput, (err) => {
if (err) {
console.error(`Failed to add the CameraInput instance. ${err.message}`);
return;
}
console.log('Callback invoked to indicate that the CameraInput instance is added.');
}); });
``` ```
### addInput ### addInput
addInput\(cameraInput: CameraInput\): Promise<void\> addInput(cameraInput: CameraInput): void
[CameraInput](#camerainput)加入到会话,通过Promise获取结果 [CameraInput](#camerainput)加入到会话。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -1273,50 +900,26 @@ addInput\(cameraInput: CameraInput\): Promise<void\> ...@@ -1273,50 +900,26 @@ addInput\(cameraInput: CameraInput\): Promise<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------ | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.addInput(cameraInput).then(() => {
console.log('Promise used to indicate that the CameraInput instance is added.');
})
```
### removeInput
removeInput\(cameraInput: CameraInput, callback: AsyncCallback<void\>\): void
移除[CameraInput](#camerainput),通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | --------------------------- | ---- | ------------------------ |
| cameraInput | [CameraInput](#camerainput) | 是 | 需要移除的CameraInput实例。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
```js ```js
captureSession.removeInput(cameraInput, (err) => { try {
if (err) { captureSession.addInput(cameraInput);
console.error(`Failed to remove the CameraInput instance. ${err.message}`); } catch (error) {
return; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log('Callback invoked to indicate that the cameraInput instance is removed.'); }
});
``` ```
### removeInput ### removeInput
removeInput\(cameraInput: CameraInput\): Promise<void\> removeInput(cameraInput: CameraInput): void
移除[CameraInput](#camerainput),通过Promise获取结果 移除[CameraInput](#camerainput)
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -1328,23 +931,26 @@ removeInput\(cameraInput: CameraInput\): Promise<void\> ...@@ -1328,23 +931,26 @@ removeInput\(cameraInput: CameraInput\): Promise<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------- | | ---------- | ----------------------------- |
| Promise\<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.removeInput(cameraInput).then(() => { try {
console.log('Promise returned to indicate that the cameraInput instance is removed.'); captureSession.removeInput(cameraInput);
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### addOutput ### addOutput
addOutput\(previewOutput: CameraOutput, callback: AsyncCallback<void\>\): void addOutput(previewOutput: CameraOutput): void
[CameraOutput](#cameraoutput)加入到会话,通过注册回调函数获取结果 [CameraOutput](#cameraoutput)加入到会话。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -1353,53 +959,29 @@ addOutput\(previewOutput: CameraOutput, callback: AsyncCallback<void\>\): void ...@@ -1353,53 +959,29 @@ addOutput\(previewOutput: CameraOutput, callback: AsyncCallback<void\>\): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------------- | ------------------------------- | ---- | ------------------------ | | ------------- | ------------------------------- | ---- | ------------------------ |
| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的previewoutput实例。 | | previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的previewoutput实例。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
captureSession.addOutput(previewOutput, (err) => {
if (err) {
console.error(`Failed to add output. ${err.message}`);
return;
}
console.log('Callback returned with output added.');
})
```
### addOutput
addOutput\(previewOutput: CameraOutput\): Promise<void\>
[CameraOutput](#cameraoutput)加入到会话,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------- | ------------------------------- | ---- | ------------------------- |
| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要添加的previewOutput实例。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.addOutput(previewOutput).then(() => { try {
console.log('Promise returned with cameraOutput added.'); captureSession.addOutput(previewOutput);
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### removeOutput ### removeOutput
removeOutput\(previewOutput: CameraOutput, callback: AsyncCallback<void\>\): void removeOutput(previewOutput: CameraOutput): void
从会话中移除[CameraOutput](#cameraoutput),通过注册回调函数获取结果 从会话中移除[CameraOutput](#cameraoutput)
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -1408,48 +990,22 @@ removeOutput\(previewOutput: CameraOutput, callback: AsyncCallback<void\>\): voi ...@@ -1408,48 +990,22 @@ removeOutput\(previewOutput: CameraOutput, callback: AsyncCallback<void\>\): voi
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------------- | ------------------------------- | ---- | ------------------------ | | ------------- | ------------------------------- | ---- | ------------------------ |
| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的previewoutput实例。 | | previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的previewoutput实例。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
captureSession.removeOutput(previewOutput, (err) => {
if (err) {
console.error(`Failed to remove the CameraOutput instance. ${err.message}`);
return;
}
console.log('Callback invoked to indicate that the CameraOutput instance is removed.');
});
```
### removeOutput
removeOutput(previewOutput: CameraOutput): Promise<void\>
从会话中移除[CameraOutput](#cameraoutput),通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------- | ------------------------------- | ---- | ------------------------- |
| previewOutput | [PreviewOutput](#previewoutput) | 是 | 需要移除的previewoutput实例。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------ | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.removeOutput(previewOutput).then(() => { try {
console.log('Promise returned to indicate that the CameraOutput instance is removed.'); captureSession.removeOutput(previewOutput);
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### start ### start
...@@ -1464,14 +1020,14 @@ start\(callback: AsyncCallback<void\>\): void ...@@ -1464,14 +1020,14 @@ start\(callback: AsyncCallback<void\>\): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.start((err) => { captureSession.start((err) => {
if (err) { if (err) {
console.error(`Failed to start the session ${err.message}`); console.error(`Failed to start the session ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate the session start success.'); console.log('Callback invoked to indicate the session start success.');
...@@ -1497,7 +1053,9 @@ start\(\): Promise<void\> ...@@ -1497,7 +1053,9 @@ start\(\): Promise<void\>
```js ```js
captureSession.start().then(() => { captureSession.start().then(() => {
console.log('Promise returned to indicate the session start success.'); console.log('Promise returned to indicate the session start success.');
}) }).catch((err) => {
console.error(`Failed to start the session ${err.code}`);
});
``` ```
### stop ### stop
...@@ -1512,14 +1070,14 @@ stop\(callback: AsyncCallback<void\>\): void ...@@ -1512,14 +1070,14 @@ stop\(callback: AsyncCallback<void\>\): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.stop((err) => { captureSession.stop((err) => {
if (err) { if (err) {
console.error(`Failed to stop the session ${err.message}`); console.error(`Failed to stop the session ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate the session stop success.'); console.log('Callback invoked to indicate the session stop success.');
...@@ -1538,14 +1096,16 @@ stop(): Promise<void\> ...@@ -1538,14 +1096,16 @@ stop(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.stop().then(() => { captureSession.stop().then(() => {
console.log('Promise returned to indicate the session stop success.'); console.log('Promise returned to indicate the session stop success.');
}) }).catch((err) => {
console.error(`Failed to stop the session ${err.code}`);
});
``` ```
### release ### release
...@@ -1560,14 +1120,14 @@ release\(callback: AsyncCallback<void\>\): void ...@@ -1560,14 +1120,14 @@ release\(callback: AsyncCallback<void\>\): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.release((err) => { captureSession.release((err) => {
if (err) { if (err) {
console.error(`Failed to release the CaptureSession instance ${err.message}`); console.error(`Failed to release the CaptureSession instance ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.');
...@@ -1586,69 +1146,48 @@ release(): Promise<void\> ...@@ -1586,69 +1146,48 @@ release(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.release().then(() => { captureSession.release().then(() => {
console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); console.log('Promise returned to indicate that the CaptureSession instance is released successfully.');
}) }).catch((err) => {
console.error(`Failed to release the CaptureSession instance ${err.code}`);
});
``` ```
### hasFlash ### hasFlash
hasFlash(callback: AsyncCallback<boolean\>): void hasFlash(): boolean
检测是否有闪光灯,通过注册回调函数获取结果。 检测是否有闪光灯,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | -------------------------------- |
| callback | AsyncCallback<boolean\> | 是 | 回调函数,返回true表示设备支持闪光灯。 |
**示例:**
```js
captureSession.hasFlash((err, status) => {
if (err) {
console.error(`Failed to check whether the device has flash light. ${err.message}`);
return;
}
console.log(`Callback returned with flash light support status: ${status}`);
})
```
### hasFlash
hasFlash(): Promise<boolean\>
检测是否有闪光灯,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------- | ----------------------------------------------- | | ---------- | ----------------------------- |
| Promise<boolean\> | 使用Promise的方式获取结果,返回true表示设备支持闪光灯。 | | boolean | 返回true表示设备支持闪光灯。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.hasFlash().then((status) => { try {
console.log(`Promise returned with the flash light support status: ${status}`); let status = captureSession.hasFlash();
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### isFlashModeSupported ### isFlashModeSupported
isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean\>): void isFlashModeSupported(flashMode: FlashMode): boolean
检测闪光灯模式是否支持,通过注册回调函数获取结果 检测闪光灯模式是否支持。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -1657,53 +1196,29 @@ isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean\>): v ...@@ -1657,53 +1196,29 @@ isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean\>): v
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ----------------------- | ---- | --------------------------------- | | --------- | ----------------------- | ---- | --------------------------------- |
| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | | flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 |
| callback | AsyncCallback<boolean\> | 是 | 回调函数,返回true表示支持该闪光灯模式。 |
**示例:**
```js
captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (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}`);
})
```
### isFlashModeSupported
isFlashModeSupported(flashMode: FlashMode): Promise<boolean\>
检测闪光灯模式是否支持,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ----------------------- | ---- | ------------- |
| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------- | ---------------------------------------------------- | | ---------- | ----------------------------- |
| Promise<boolean\> | 使用Promise的方式获取结果,返回true表示设备支持该闪光灯模式。 | | boolean | 返回true表示支持该闪光灯模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { try {
console.log(`Promise returned with flash mode support status.${status}`); let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### setFlashMode ### setFlashMode
setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void\>): void setFlashMode(flashMode: FlashMode): void
设置闪光灯模式,通过注册回调函数获取结果 设置闪光灯模式。
进行设置之前,需要先检查: 进行设置之前,需要先检查:
...@@ -1716,134 +1231,55 @@ setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void\>): void ...@@ -1716,134 +1231,55 @@ setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | ----------------------- | ---- | --------------------- | | --------- | ----------------------- | ---- | --------------------- |
| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 | | flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ----------------------------- |
| [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { try {
if (err) { captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
console.error(`Failed to set the flash mode ${err.message}`); } catch (error) {
return; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log('Callback returned with the successful execution of setFlashMode.'); }
})
``` ```
### setFlashMode ### getFlashMode
setFlashMode(flashMode: FlashMode): Promise<void\> getFlashMode(): FlashMode
设置闪光灯模式,通过Promise获取结果。 获取当前设备的闪光灯模式。
进行设置之前,需要先检查:
1. 设备是否支持闪光灯,可使用方法[hasFlash](#hasflash)
2. 设备是否支持指定的闪光灯模式,可使用方法[isFlashModeSupported](#isflashmodesupported)
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ----------------------- | ---- | ------------- |
| flashMode | [FlashMode](#flashmode) | 是 | 指定闪光灯模式。 |
**返回值:**
| 类型 | 说明 |
| -------------- | ------------------------ |
| Promise<void\> | 使用Promise的方式获取结果。 |
**示例:**
```js
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => {
console.log('Promise returned with the successful execution of setFlashMode.');
})
```
### getFlashMode
getFlashMode(callback: AsyncCallback<FlashMode\>): void
获取当前设备的闪光灯模式,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | --------------------------------- |
| callback | AsyncCallback<[FlashMode](#flashmode)\> | 是 | 回调函数,用于获取当前设备的闪光灯模式。 |
**示例:**
```js
captureSession.getFlashMode((err, flashMode) => {
if (err) {
console.error(`Failed to get the flash mode ${err.message}`);
return;
}
console.log(`Callback returned with current flash mode: ${flashMode}`);
})
```
### getFlashMode
getFlashMode(): Promise<FlashMode\>
获取当前设备的闪光灯模式,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| --------------------------------- | --------------------------------- | | ---------- | ----------------------------- |
| Promise<[FlashMode](#flashmode)\> | 使用Promise的方式获取当前的闪光灯模式。 | | [FlashMode](#flashmode) | 获取当前设备的闪光灯模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.getFlashMode().then((flashMode) => {
console.log(`Promise returned with current flash mode : ${flashMode}`);
})
```
### isExposureModeSupported
isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback<boolean\>): void;
检测曝光模式是否支持,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------| ---- | ----------------------------- |
| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 |
| callback | AsyncCallback<boolean\> | 是 | 回调函数,用于获取是否支持曝光模式。 |
**示例:** **示例:**
```js ```js
captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => { try {
if (err) { let flashMode = captureSession.getFlashMode();
console.log(`Failed to check exposure mode supported ${err.message}`); } catch (error) {
return ; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log('Callback returned with the successful execution of isExposureModeSupported'); }
})
``` ```
### isExposureModeSupported ### isExposureModeSupported
isExposureModeSupported(aeMode: ExposureMode): Promise<boolean\> isExposureModeSupported(aeMode: ExposureMode): boolean;
检测曝光模式是否支持,通过Promise获取结果 检测曝光模式是否支持。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -1855,71 +1291,51 @@ isExposureModeSupported(aeMode: ExposureMode): Promise<boolean\> ...@@ -1855,71 +1291,51 @@ isExposureModeSupported(aeMode: ExposureMode): Promise<boolean\>
**返回值:** **返回值:**
| 名称 | 说明 | | 类型 | 说明 |
| ----------------- |--------------------------------- | | ---------- | ----------------------------- |
| Promise<boolean\> | 使用Promise的方式获取支持的曝光模式。 | | boolean | 获取是否支持曝光模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => {
console.log(`Promise returned with exposure mode supported : ${isSupported}`);
})
```
### getExposureMode
getExposureMode(callback: AsyncCallback<ExposureMode\>): void
获取当前曝光模式,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------| ---- | ---------------------------------------- |
| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | 是 | 回调函数,用于获取当前曝光模式。 |
**示例:** **示例:**
```js ```js
captureSession.getExposureMode((err, exposureMode) => { try {
if (err) { let isSupported = captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED);
console.log(`Failed to get the exposure mode ${err.message}`); } catch (error) {
return ; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log(`Callback returned with current exposure mode: ${exposureMode}`); }
})
``` ```
### getExposureMode ### getExposureMode
getExposureMode(): Promise<ExposureMode\> getExposureMode(): ExposureMode
获取当前曝光模式,通过Promise获取结果 获取当前曝光模式。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 名称 | 说明 | | 类型 | 说明 |
| --------------------------------------- |------------------------------- | | ---------- | ----------------------------- |
| Promise<[ExposureMode](#exposuremode)\> | 使用Promise的方式获取当前曝光模式。 | | [ExposureMode](#exposuremode) | 获取当前曝光模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.getExposureMode().then((exposureMode) => { try {
console.log(`Promise returned with current exposure mode : ${exposureMode}`); let exposureMode = captureSession.getExposureMode();
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### setExposureMode ### setExposureMode
setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void\>): void setExposureMode(aeMode: ExposureMode): void
设置曝光模式,通过注册回调函数获取结果 设置曝光模式。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -1928,124 +1344,54 @@ setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void\>): void ...@@ -1928,124 +1344,54 @@ setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------| ---- | ----------------------- | | -------- | -------------------------------| ---- | ----------------------- |
| aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 | | aeMode | [ExposureMode](#exposuremode) | 是 | 曝光模式。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取设置结果。 |
**示例:**
```js
captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => {
if (err) {
console.log(`Failed to set the exposure mode ${err.message}`);
return ;
}
console.log('Callback returned with the successful execution of setExposureMode');
})
```
### setExposureMode
setExposureMode(aeMode: ExposureMode): Promise<void\>
设置曝光模式,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 名称 | 说明 | | 类型 | 说明 |
| ----------------- |---------------------------- | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取设置结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => {
console.log('Promise returned with the successful execution of setExposureMode.');
})
```
### getMeteringPoint
getMeteringPoint(callback: AsyncCallback<Point\>): void
查询曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留,将在3.2版本开放)
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------| ---- | ------------------------ |
| callback | AsyncCallback<[Point](#point)\>| 是 | 回调函数,用于获取当前曝光点。 |
**示例:** **示例:**
```js ```js
captureSession.getMeteringPoint((err, exposurePoint) => { try {
if (err) { captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED);
console.log(`Failed to get the current exposure point ${err.message}`); } catch (error) {
return ; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log(`Callback returned with current exposure point: ${exposurePoint}`); }
})
``` ```
### getMeteringPoint ### getMeteringPoint
getMeteringPoint(): Promise<Point\> getMeteringPoint(): Point
查询曝光区域中心点,通过Promise获取结果。(该接口目前为预留,将在3.2版本开放) 查询曝光区域中心点。(该接口目前为预留,将在3.2版本开放)
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 名称 | 说明 | | 类型 | 说明 |
| ------------------------- |----------------------------- | | ---------- | ----------------------------- |
| Promise<[Point](#point)\> | 使用Promise的方式获取当前曝光点。 | | [Point](#point) | 获取当前曝光点。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.getMeteringPoint().then((exposurePoint) => {
console.log(`Promise returned with current exposure point : ${exposurePoint}`);
})
```
### setMeteringPoint
setMeteringPoint(point: Point, callback: AsyncCallback<void\>): void
设置曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留,将在3.2版本开放)
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------- | -------------------------------| ---- | ------------------- |
| exposurePoint | [Point](#point) | 是 | 曝光点。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
```js ```js
const Point1 = {x: 1, y: 1}; try {
let exposurePoint = captureSession.getMeteringPoint();
captureSession.setMeteringPoint(Point1,(err) => { } catch (error) {
if (err) { // 失败返回错误码error.code并处理
console.log(`Failed to set the exposure point ${err.message}`); console.log(error.code);
return ; }
}
console.log('Callback returned with the successful execution of setMeteringPoint');
})
``` ```
### setMeteringPoint ### setMeteringPoint
setMeteringPoint(point: Point): Promise<void\> setMeteringPoint(point: Point): void
设置曝光区域中心点,通过Promise获取结果。(该接口目前为预留,将在3.2版本开放) 设置曝光区域中心点。(该接口目前为预留,将在3.2版本开放)
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -2057,73 +1403,52 @@ setMeteringPoint(point: Point): Promise<void\> ...@@ -2057,73 +1403,52 @@ setMeteringPoint(point: Point): Promise<void\>
**返回值:** **返回值:**
| 名称 | 说明 | | 类型 | 说明 |
| ----------------- |------------------------ | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式返回结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
const Point2 = {x: 2, y: 2};
captureSession.setMeteringPoint(Point2).then(() => {
console.log('Promise returned with the successful execution of setMeteringPoint');
})
```
### getExposureBiasRange
getExposureBiasRange(callback: AsyncCallback<Array<number\>\>): void
查询曝光补偿范围,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------| ---- | ----------------------------- |
| callback | AsyncCallback<Array<number\>\> | 是 | 回调函数,用于获取补偿范围的数组。 |
**示例:** **示例:**
```js ```js
captureSession.getExposureBiasRange((err, biasRangeArray) => { const exposurePoint = {x: 1, y: 1};
if (err) { try {
console.log(`Failed to get the array of compenstation range ${err.message}`); captureSession.setMeteringPoint(exposurePoint);
return ; } catch (error) {
} // 失败返回错误码error.code并处理
console.log('Callback returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); console.log(error.code);
}) }
``` ```
### getExposureBiasRange ### getExposureBiasRange
getExposureBiasRange(): Promise<Array<number\>\> getExposureBiasRange(): Array<number\>
查询曝光补偿范围,通过Promise获取结果 查询曝光补偿范围。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 名称 | 说明 | | 类型 | 说明 |
| ----------------- |-------------------------------------- | | ---------- | ----------------------------- |
| Promise<Array<number\>\> | 使用Promise的方式获取曝光补偿范围。 | | Array<number\> | 获取补偿范围的数组。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.getExposureBiasRange().then((biasRangeArray) => { try {
console.log('Promise returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); let biasRangeArray = captureSession.getExposureBiasRange();
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### setExposureBias ### setExposureBias
setExposureBias(exposureBias: number, callback: AsyncCallback<void\>): void setExposureBias(exposureBias: number): void
设置曝光补偿,通过注册回调函数获取结果 设置曝光补偿。
进行设置之前,建议先通过方法[getExposureBiasRange](#getexposurebiasrange)查询支持的范围。 进行设置之前,建议先通过方法[getExposureBiasRange](#getexposurebiasrange)查询支持的范围。
...@@ -2133,106 +1458,50 @@ setExposureBias(exposureBias: number, callback: AsyncCallback<void\>): void ...@@ -2133,106 +1458,50 @@ setExposureBias(exposureBias: number, callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------| ---- | ------------------- | | -------- | -------------------------------| ---- | ------------------- |
| exposureBias | number | 是 | 曝光补偿,getExposureBiasRange查询支持的范围 | | exposureBias | number | 是 | 曝光补偿,getExposureBiasRange查询支持的范围,接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
let exposureBias = biasRangeArray[0];
captureSession.setExposureBias(exposureBias,(err) => {
if (err) {
console.log(`Failed to set the exposure bias ${err.message}`);
return ;
}
console.log('Callback returned with the successful execution of setExposureBias');
})
```
### setExposureBias
setExposureBias(exposureBias: number): Promise<void\>
设置曝光补偿,通过Promise获取结果。
进行设置之前,建议先通过方法[getExposureBiasRange](#getexposurebiasrange)查询支持的范围。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------------- | --------- | ---- | --------- |
| exposureBias | number | 是 | 曝光补偿,getExposureBiasRange查询支持的范围 |
**返回值:**
| 名称 | 说明 |
| ----------------- |------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 |
**示例:** **示例:**
```js ```js
let exposureBias = biasRangeArray[0]; let exposureBias = biasRangeArray[0];
captureSession.setExposureBias(exposureBias).then(() => { try {
console.log('Promise returned with the successful execution of setExposureBias.'); captureSession.setExposureBias(exposureBias);
}) } catch (error) {
``` // 失败返回错误码error.code并处理
console.log(error.code);
### getExposureValue }
getExposureValue(callback: AsyncCallback<number\>): void
查询当前曝光值,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------| ---- | --------------------- |
| callback | AsyncCallback<number\> | 是 | 回调函数,用于获取曝光值。 |
**示例:**
```js
captureSession.getExposureValue((err, exposureValue) => {
if (err) {
console.log(`Failed to get the exposure value ${err.message}`);
return ;
}
console.log(`Callback returned with the exposure value: ${exposureValue}`);
})
``` ```
### getExposureValue ### getExposureValue
getExposureValue(): Promise<number\> getExposureValue(): number
查询当前曝光值,通过Promise获取结果 查询当前曝光值。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 名称 | 说明 | | 类型 | 说明 |
| ----------------- |-------------------------- | | ---------- | ----------------------------- |
| Promise<number\> | 使用Promise的方式获取曝光值。 | | number | 获取曝光值。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.getExposureValue().then((exposureValue) => { try {
console.log(`Promise returned with exposure value: ${exposureValude}`); let exposureValue = captureSession.getExposureValue();
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### isFocusModeSupported ### isFocusModeSupported
isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean\>): void isFocusModeSupported(afMode: FocusMode): boolean
检测对焦模式是否支持,通过注册回调函数获取结果 检测对焦模式是否支持。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -2241,53 +1510,29 @@ isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean\>): void ...@@ -2241,53 +1510,29 @@ isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | -------------------------------- | | -------- | ----------------------- | ---- | -------------------------------- |
| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | | afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 |
| callback | AsyncCallback<boolean\> | 是 | 回调函数,返回true表示支持该焦距模式。 |
**示例:**
```js
captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (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}`);
})
```
### isFocusModeSupported
isFocusModeSupported(afMode: FocusMode): Promise<boolean\>
检测对焦模式是否支持,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------- | ---- | ------------- |
| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------------- | --------------------------------------------------- | | ---------- | ----------------------------- |
| Promise<boolean\> | 使用Promise的方式获取结果,返回true表示设备支持该焦距模式。 | | boolean | 返回true表示支持该焦距模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { try {
console.log(`Promise returned with focus mode support status ${status}.`); let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO);
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### setFocusMode ### setFocusMode
setFocusMode(afMode: FocusMode, callback: AsyncCallback<void\>): void setFocusMode(afMode: FocusMode): void
设置对焦模式,通过注册回调函数获取结果 设置对焦模式。
进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported) 进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)
...@@ -2298,132 +1543,54 @@ setFocusMode(afMode: FocusMode, callback: AsyncCallback<void\>): void ...@@ -2298,132 +1543,54 @@ setFocusMode(afMode: FocusMode, callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ------------------- | | -------- | ----------------------- | ---- | ------------------- |
| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 | | afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => {
if (err) {
console.error(`Failed to set the focus mode ${err.message}`);
return;
}
console.log('Callback returned with the successful execution of setFocusMode.');
})
```
### setFocusMode
setFocusMode(afMode: FocusMode): Promise<void\>
设置对焦模式,通过Promise获取结果。
进行设置之前,需要先检查设备是否支持指定的焦距模式,可使用方法[isFocusModeSupported](#isfocusmodesupported)
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------- | ---- | ------------- |
| afMode | [FocusMode](#focusmode) | 是 | 指定的焦距模式。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------ | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => {
console.log('Promise returned with the successful execution of setFocusMode.');
})
```
### getFocusMode
getFocusMode(callback: AsyncCallback<FocusMode\>): void
获取当前的对焦模式,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ------------------------------- |
| callback | AsyncCallback<[FocusMode](#focusmode)\> | 是 | 回调函数,用于获取当前设备的焦距模式。 |
**示例:** **示例:**
```js ```js
captureSession.getFocusMode((err, afMode) => { try {
if (err) { captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO);
console.error(`Failed to get the focus mode ${err.message}`); } catch (error) {
return; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log(`Callback returned with current focus mode: ${afMode}`); }
})
``` ```
### getFocusMode ### getFocusMode
getFocusMode(): Promise<FocusMode\> getFocusMode(): FocusMode
获取当前的对焦模式,通过Promise获取结果 获取当前的对焦模式。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------- | -------------------------------- | | ---------- | ----------------------------- |
| Promise<FocusMode\> | 使用Promise的方式获取当前的焦距模式。 | | [FocusMode](#focusmode) | 获取当前设备的焦距模式。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.getFocusMode().then((afMode) => {
console.log(`Promise returned with current focus mode : ${afMode}`);
})
```
### setFocusPoint
setFocusPoint(point: Point, callback: AsyncCallback<void\>): void
设置焦点,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ------------------- |
| point | [Point](#point) | 是 | 焦点。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
```js ```js
const Point1 = {x: 1, y: 1}; try {
let afMode = captureSession.getFocusMode();
captureSession.setFocusPoint(Point1, (err) => { } catch (error) {
if (err) { // 失败返回错误码error.code并处理
console.error(`Failed to set the focus point ${err.message}`); console.log(error.code);
return; }
}
console.log('Callback returned with the successful execution of setFocusPoint.');
})
``` ```
### setFocusPoint ### setFocusPoint
setFocusPoint(point: Point): Promise<void\> setFocusPoint(point: Point): void
设置焦点,通过Promise获取结果 设置焦点。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -2431,173 +1598,106 @@ setFocusPoint(point: Point): Promise<void\> ...@@ -2431,173 +1598,106 @@ setFocusPoint(point: Point): Promise<void\>
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ------------------- | | -------- | ----------------------- | ---- | ------------------- |
| point | [Point](#point) | 是 | 焦点。 | | Point1 | [Point](#point) | 是 | 焦点。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
const Point2 = {x: 2, y: 2};
captureSession.setFocusPoint(Point2).then(() => {
console.log('Promise returned with the successful execution of setFocusPoint.');
})
```
### getFocusPoint
getFocusPoint(callback: AsyncCallback<Point\>): void
查询焦点,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ----------------------- |
| callback | AsyncCallback<[Point](#point)\> | 是 | 回调函数,用于获取当前焦点。 |
**示例:** **示例:**
```js ```js
captureSession.getFocusPoint((err, point) => { const Point1 = {x: 1, y: 1};
if (err) { try {
console.error(`Failed to get the current focus point ${err.message}`); captureSession.setFocusPoint(Point1);
return; } catch (error) {
} // 失败返回错误码error.code并处理
console.log('Callback returned with the current focus point: ' + JSON.stringify(point)); console.log(error.code);
}) }
``` ```
### getFocusPoint ### getFocusPoint
getFocusPoint(): Promise<Point\> getFocusPoint(): Point
查询焦点,通过Promise获取结果 查询焦点。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| --------------- | --------------------------- | | ---------- | ----------------------------- |
| Promise<Point\> | 使用Promise的方式获取当前焦点。 | | [Point](#point) | 用于获取当前焦点。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.getFocusPoint().then((point) => {
console.log('Promise returned with the current focus point: ' + JSON.stringify(point));
})
```
### getFocalLength
getFocalLength(callback: AsyncCallback<number\>): void
查询焦距值,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ----------------------- |
| callback | AsyncCallback<number\> | 是 | 回调函数,用于获取当前焦距。 |
**示例:** **示例:**
```js ```js
captureSession.getFocalLength((err, focalLength) => { try {
if (err) { let point = captureSession.getFocusPoint();
console.error(`Failed to get the current focal length ${err.message}`); } catch (error) {
return; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log(`Callback returned with the current focal length: ${focalLength}`); }
})
``` ```
### getFocalLength ### getFocalLength
getFocalLength(): Promise<number\> getFocalLength(): number
查询焦距值,通过Promise获取结果 查询焦距值。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ---------------- | ----------------------- | | ---------- | ----------------------------- |
| Promise<number\> | 使用Promise的方式获取焦距。 | | number | 用于获取当前焦距。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.getFocalLength().then((focalLength) => {
console.log(`Promise returned with the current focal length: ${focalLength}`);
})
```
### getZoomRatioRange
getZoomRatioRange\(callback: AsyncCallback<Array<number\>\>\): void
获取支持的变焦范围,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------ | ---- | ------------------- |
| callback | AsyncCallback<Array<number\>\> | 是 | 回调函数,用于获取可变焦距比范围,返回的数组包括其最小值和最大值。 |
**示例:** **示例:**
```js ```js
captureSession.getZoomRatioRange((err, zoomRatioRange) => { try {
if (err) { let focalLength = captureSession.getFocalLength();
console.error(`Failed to get the zoom ratio range. ${err.message}`); } catch (error) {
return; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log(`Callback returned with zoom ratio range: ${zoomRatioRange.length}`); }
})
``` ```
### getZoomRatioRange ### getZoomRatioRange
getZoomRatioRange\(\): Promise<Array<number\>\> getZoomRatioRange(): Array<number\>
获取支持的变焦范围,通过Promise获取结果 获取支持的变焦范围。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------ | --------------------------- | | ---------- | ----------------------------- |
| Promise<Array<number\>\> | 使用Promise的方式获取当前的可变焦距比范围,返回的数组包括其最小值和最大值。 | | Array<number\> | 用于获取可变焦距比范围,返回的数组包括其最小值和最大值。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.getZoomRatioRange().then((zoomRatioRange) => { try {
console.log(`Promise returned with zoom ratio range: ${zoomRatioRange.length}`); let zoomRatioRange = captureSession.getZoomRatioRange();
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### setZoomRatio ### setZoomRatio
setZoomRatio(zoomRatio: number, callback: AsyncCallback<void\>): void setZoomRatio(zoomRatio: number): void
设置变焦比,通过注册回调函数获取结果 设置变焦比。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -2606,227 +1706,111 @@ setZoomRatio(zoomRatio: number, callback: AsyncCallback<void\>): void ...@@ -2606,227 +1706,111 @@ setZoomRatio(zoomRatio: number, callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | -------------------- | ---- | ------------------- | | --------- | -------------------- | ---- | ------------------- |
| zoomRatio | number | 是 | 可变焦距比,通过getZoomRatioRange获取支持的变焦范围 | | zoomRatio | number | 是 | 可变焦距比,通过getZoomRatioRange获取支持的变焦范围 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
let zoomRatio = zoomRatioRange[0];
captureSession.setZoomRatio(zoomRatio, (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.');
})
```
### setZoomRatio
setZoomRatio(zoomRatio: number): Promise<void\>
设置变焦比,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | --------- |
| zoomRatio | number | 是 | 可变焦距比,通过getZoomRatioRange获取支持的变焦范围|
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
let zoomRatio = zoomRatioRange[0]; let zoomRatio = zoomRatioRange[0];
captureSession.setZoomRatio(zoomRatio).then(() => { try {
console.log('Promise returned with the successful execution of setZoomRatio.'); captureSession.setZoomRatio(zoomRatio);
}) } catch (error) {
``` // 失败返回错误码error.code并处理
console.log(error.code);
### getZoomRatio }
getZoomRatio(callback: AsyncCallback<number\>): void
获取当前的变焦比,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------------- |
| callback | AsyncCallback<number\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
captureSession.getZoomRatio((err, zoomRatio) => {
if (err) {
console.error(`Failed to get the zoom ratio ${err.message}`);
return;
}
console.log(`Callback returned with current zoom ratio: ${zoomRatio}`);
})
``` ```
### getZoomRatio ### getZoomRatio
getZoomRatio(): Promise<number\> getZoomRatio(): number
获取当前的变焦比,通过Promise获取结果 获取当前的变焦比。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ---------------- | ----------------------- | | ---------- | ----------------------------- |
| Promise<number\> | 使用Promise的方式获取结果。 | | number | 获取当前的变焦比结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
captureSession.getZoomRatio().then((zoomRatio) => {
console.log(`Promise returned with current zoom ratio : ${zoomRatio}`);
})
```
### isVideoStabilizationModeSupported
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback<boolean\>): void
查询是否支持指定的视频防抖模式,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------------------ |
| vsMode | [VideoStabilizationMode](#videostabilizationmode) | 是 | 视频防抖模式。 |
| callback | AsyncCallback<boolean\> | 是 | 回调函数,返回视频防抖模式是否支持。 |
**示例:**
```js
captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF, (err, isSupported) => {
if (err) {
console.error(`Failed to check whether video stabilization mode supported. ${err.message}`);
return;
}
console.log(`Callback returned with the successful execution of isVideoStabilizationModeSupported`);
})
```
### isVideoStabilizationModeSupported
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise<boolean\>
查询是否支持指定的视频防抖模式,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:**
| 类型 | 说明 |
| ----------------- | --------------------------------------------- |
| Promise<boolean\> | 使用Promise的方式获取结果,返回视频防抖模式是否支持。 |
**示例:**
```js
captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF).then((isSupported) => {
console.log(`Promise returned with video stabilization mode supported: ${isSupported}`);
})
```
### getActiveVideoStabilizationMode
getActiveVideoStabilizationMode(callback: AsyncCallback<VideoStabilizationMode\>): void
查询当前正在使用的视频防抖模式,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<VideoStabilizationMode\> | 是 | 回调函数,返回视频防抖是否正在使用。 |
**示例:** **示例:**
```js ```js
captureSession.getActiveVideoStabilizationMode((err, vsMode) => { try {
if (err) { let zoomRatio = captureSession.getZoomRatio();
console.error(`Failed to get active video stabilization mode ${err.message}`); } catch (error) {
return; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log('Callback returned with the successful execution of getActiveVideoStabilizationMode.'); }
})
``` ```
### getActiveVideoStabilizationMode ### isVideoStabilizationModeSupported
getActiveVideoStabilizationMode(): Promise<VideoStabilizationMode\> isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean
查询当前正在使用的视频防抖模式,通过Promise获取结果 查询是否支持指定的视频防抖模式
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ------------------------------ |
| vsMode | [VideoStabilizationMode](#videostabilizationmode) | 是 | 视频防抖模式。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------------------------- | ------------------------------------------------- | | ---------- | ----------------------------- |
| Promise<VideoStabilizationMode\> | 使用Promise的方式获取结果,返回视频防抖当前是否正在使用。 | | boolean | 返回视频防抖模式是否支持。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.getActiveVideoStabilizationMode().then((vsMode) => { try {
console.log(`Promise returned with the current video stabilization mode: ${vsMode}`); let isSupported = captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF);
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### setVideoStabilizationMode ### getActiveVideoStabilizationMode
setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback<void\>): void getActiveVideoStabilizationMode(): VideoStabilizationMode
设置视频防抖模式,通过注册回调函数获取结果 查询当前正在使用的视频防抖模式
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:** **返回值:**
| 参数名 | 类型 | 必填 | 说明 | | 类型 | 说明 |
| -------- | ------------------------------------------------- | ---- | --------------------- | | ---------- | ----------------------------- |
| mode | [VideoStabilizationMode](#videostabilizationmode) | 是 | 需要设置的视频防抖模式。 | | VideoStabilizationMode | 视频防抖是否正在使用。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
| callback | AsyncCallback<void\> | 是 | 回调函数。 |
**示例:** **示例:**
```js ```js
captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF, (err) => { try {
if (err) { let vsMode = captureSession.getActiveVideoStabilizationMode();
console.error(`Failed to set the video stabilization mode ${err.message}`); } catch (error) {
return; // 失败返回错误码error.code并处理
} console.log(error.code);
console.log('Callback returned with the successful execution of setVideoStabilizationMode.'); }
})
``` ```
### setVideoStabilizationMode ### setVideoStabilizationMode
setVideoStabilizationMode(mode: VideoStabilizationMode): Promise<void\> setVideoStabilizationMode(mode: VideoStabilizationMode): void
设置视频防抖,通过Promise获取结果 设置视频防抖模式
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -2838,23 +1822,26 @@ setVideoStabilizationMode(mode: VideoStabilizationMode): Promise<void\> ...@@ -2838,23 +1822,26 @@ setVideoStabilizationMode(mode: VideoStabilizationMode): Promise<void\>
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------------------------------- | | ---------- | ----------------------------- |
| Promise<void\> | 使用Promise的方式获取结果,返回设置的视频防抖模式的结果。 | | [CameraErrorCode](#cameraerrorcode) | 接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF).then(() => { try {
console.log('Promise returned with the successful execution of setVideoStabilizationMode.'); captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF);
}) } catch (error) {
// 失败返回错误码error.code并处理
console.log(error.code);
}
``` ```
### on('focusStateChange') ### on('focusStateChange')
on(type: 'focusStateChange', callback: AsyncCallback<FocusState\>): void on(type: 'focusStateChange', callback: AsyncCallback<FocusState\>): void
监听焦距的状态变化,通过注册回调函数获取结果。 监听相机聚焦的状态变化,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -2862,7 +1849,7 @@ on(type: 'focusStateChange', callback: AsyncCallback<FocusState\>): void ...@@ -2862,7 +1849,7 @@ on(type: 'focusStateChange', callback: AsyncCallback<FocusState\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------- | ---- | ------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------ |
| type | string | 是 | 监听事件,固定为'focusStateChange',即焦距状态变化事件。 | | type | string | 是 | 监听事件,固定为'focusStateChange',callback 返回聚焦状态改变信息,session 创建成功可监听。 |
| callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 | | callback | AsyncCallback<[FocusState](#focusstate)\> | 是 | 回调函数,用于获取焦距状态。 |
**示例:** **示例:**
...@@ -2875,7 +1862,7 @@ captureSession.on('focusStateChange', (focusState) => { ...@@ -2875,7 +1862,7 @@ captureSession.on('focusStateChange', (focusState) => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<CaptureSessionError\>): void on(type: 'error', callback: ErrorCallback<BusinessError\>): void
监听拍照会话的错误事件,通过注册回调函数获取结果。 监听拍照会话的错误事件,通过注册回调函数获取结果。
...@@ -2885,39 +1872,17 @@ on(type: 'error', callback: ErrorCallback<CaptureSessionError\>): void ...@@ -2885,39 +1872,17 @@ on(type: 'error', callback: ErrorCallback<CaptureSessionError\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------ | | -------- | ----------------------------------------------------------- | ---- | ------------------------------ |
| type | string | 是 | 监听事件,固定为'error',即拍照会话错误事件。 | | type | string | 是 | 监听事件,固定为'error',callback返回session接口使用错误返回对应错误码,比如调用(beginConfig(),commitConfig(),addInput)等接口发生错误时返回对应错误码。 |
| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | 是 | 回调函数,用于获取错误信息。 | | callback | ErrorCallback<BusinessError\> | 是 | 回调函数,用于获取错误信息。返回错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
captureSession.on('error', (captureSessionError) => { captureSession.on('error', (error) => {
console.log(`Capture session error code: ${captureSessionError.code}`); console.log(`Capture session error code: ${error.code}`);
}) })
``` ```
## CaptureSessionErrorCode
枚举,会话错误类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 |
| ----------------------------- | ---- | -------- |
| ERROR_UNKNOWN | -1 | 未知错误。 |
| ERROR_INSUFFICIENT_RESOURCES | 0 | 资源不足。 |
| ERROR_TIMEOUT | 1 | 超时。 |
## CaptureSessionError
会话错误码。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 类型 | 必填 | 说明 |
| ---- | ------------------------------------------- | -------------------------- |-------------------------- |
| code | [CaptureSessionError](#capturesessionerror) | 是 |CaptureSession中的错误码。 |
## CameraOutput ## CameraOutput
会话中[CaptureSession](#capturesession)使用的输出信息,output的基类。 会话中[CaptureSession](#capturesession)使用的输出信息,output的基类。
...@@ -2938,14 +1903,14 @@ start(callback: AsyncCallback<void\>): void ...@@ -2938,14 +1903,14 @@ start(callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
previewOutput.start((err) => { previewOutput.start((err) => {
if (err) { if (err) {
console.error(`Failed to start the previewOutput. ${err.message}`); console.error(`Failed to start the previewOutput. ${err.code}`);
return; return;
} }
console.log('Callback returned with previewOutput started.'); console.log('Callback returned with previewOutput started.');
...@@ -2964,14 +1929,16 @@ start(): Promise<void\> ...@@ -2964,14 +1929,16 @@ start(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode)|
**示例:** **示例:**
```js ```js
previewOutput.start().then(() => { previewOutput.start().then(() => {
console.log('Promise returned with previewOutput started.'); console.log('Promise returned with previewOutput started.');
}) }).catch((err) => {
console.log('Failed to previewOutput start '+ err.code);
});
``` ```
### stop ### stop
...@@ -2993,7 +1960,7 @@ stop(callback: AsyncCallback<void\>): void ...@@ -2993,7 +1960,7 @@ stop(callback: AsyncCallback<void\>): void
```js ```js
previewOutput.stop((err) => { previewOutput.stop((err) => {
if (err) { if (err) {
console.error(`Failed to stop the previewOutput. ${err.message}`); console.error(`Failed to stop the previewOutput. ${err.code}`);
return; return;
} }
console.log('Callback returned with previewOutput stopped.'); console.log('Callback returned with previewOutput stopped.');
...@@ -3019,7 +1986,9 @@ stop(): Promise<void\> ...@@ -3019,7 +1986,9 @@ stop(): Promise<void\>
```js ```js
previewOutput.stop().then(() => { previewOutput.stop().then(() => {
console.log('Callback returned with previewOutput stopped.'); console.log('Callback returned with previewOutput stopped.');
}) }).catch((err) => {
console.log('Failed to previewOutput stop '+ err.code);
});
``` ```
### release ### release
...@@ -3034,14 +2003,14 @@ release(callback: AsyncCallback<void\>): void ...@@ -3034,14 +2003,14 @@ release(callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
previewOutput.release((err) => { previewOutput.release((err) => {
if (err) { if (err) {
console.error(`Failed to release the PreviewOutput instance ${err.message}`); console.error(`Failed to release the PreviewOutput instance ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
...@@ -3060,14 +2029,16 @@ release(): Promise<void\> ...@@ -3060,14 +2029,16 @@ release(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
previewOutput.release().then(() => { previewOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
}) }).catch((err) => {
console.log('Failed to previewOutput release '+ err.code);
});
``` ```
### on('frameStart') ### on('frameStart')
...@@ -3082,7 +2053,7 @@ on(type: 'frameStart', callback: AsyncCallback<void\>): void ...@@ -3082,7 +2053,7 @@ on(type: 'frameStart', callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | --------------------------------------- | | -------- | -------------------- | ---- | --------------------------------------- |
| type | string | 是 | 监听事件,固定为'frameStart',即帧启动事件。 | | type | string | 是 | 监听事件,固定为'frameStart',预览开始第一帧返回,previewOutput创建成功可监听。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
...@@ -3105,7 +2076,7 @@ on(type: 'frameEnd', callback: AsyncCallback<void\>): void ...@@ -3105,7 +2076,7 @@ on(type: 'frameEnd', callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------------------------- | | -------- | -------------------- | ---- | ------------------------------------- |
| type | string | 是 | 监听事件,固定为'frameEnd',即帧结束事件。 | | type | string | 是 | 监听事件,固定为'frameEnd',预览结束最后一帧返回,previewOutput创建成功可监听。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
...@@ -3118,7 +2089,7 @@ previewOutput.on('frameEnd', () => { ...@@ -3118,7 +2089,7 @@ previewOutput.on('frameEnd', () => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<PreviewOutputError\>): void on(type: 'error', callback: ErrorCallback<BusinessError\>): void
监听预览输出的错误事件,通过注册回调函数获取结果。 监听预览输出的错误事件,通过注册回调函数获取结果。
...@@ -3128,8 +2099,8 @@ on(type: 'error', callback: ErrorCallback<PreviewOutputError\>): void ...@@ -3128,8 +2099,8 @@ on(type: 'error', callback: ErrorCallback<PreviewOutputError\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------------- | ---- | ------------------------ | | -------- | ----------------------------------------------------------------- | ---- | ------------------------ |
| type | string | 是 | 监听事件,固定为'error',即预览输出错误事件。| | type | string | 是 | 监听事件,固定为'error',callback返回预览接口使用错误时的错误码,比如调用(start(),release())等接口发生错误时返回对应错误码。|
| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | 是 | 回调函数,用于获取错误信息。 | | callback | ErrorCallback<BusinessError\> | 是 | 回调函数,用于获取错误信息。返回错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
...@@ -3139,26 +2110,6 @@ previewOutput.on('error', (previewOutputError) => { ...@@ -3139,26 +2110,6 @@ previewOutput.on('error', (previewOutputError) => {
}) })
``` ```
## PreviewOutputErrorCode
枚举,预览输出错误类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 |
| ------------- | ---- | -------- |
| ERROR_UNKNOWN | -1 | 未知错误。 |
## PreviewOutputError
预览输出错误码。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 类型 | 必填 | 说明 |
| ---- | ------------------------------------------------- | ---------------- |---------------------- |
| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | 是 |PreviewOutput中的错误码。 |
## ImageRotation ## ImageRotation
枚举,图片旋转角度。 枚举,图片旋转角度。
...@@ -3226,14 +2177,14 @@ capture(callback: AsyncCallback<void\>): void ...@@ -3226,14 +2177,14 @@ capture(callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
photoOutput.capture((err) => { photoOutput.capture((err) => {
if (err) { if (err) {
console.error(`Failed to capture the photo ${err.message}`); console.error(`Failed to capture the photo ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate the photo capture request success.'); console.log('Callback invoked to indicate the photo capture request success.');
...@@ -3242,6 +2193,30 @@ photoOutput.capture((err) => { ...@@ -3242,6 +2193,30 @@ photoOutput.capture((err) => {
### capture ### capture
capture(): Promise<void\>
以默认设置触发一次拍照,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:**
| 类型 | 说明 |
| -------------- | ------------------------ |
| Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:**
```js
photoOutput.capture().then(() => {
console.log('Promise returned to indicate that photo capture request success.');
}).catch((err) => {
console.log('Failed to photoOutput capture '+ err.code);
});
```
### capture
capture(setting: PhotoCaptureSetting, callback: AsyncCallback<void\>): void capture(setting: PhotoCaptureSetting, callback: AsyncCallback<void\>): void
以指定参数触发一次拍照,通过注册回调函数获取结果。 以指定参数触发一次拍照,通过注册回调函数获取结果。
...@@ -3253,7 +2228,7 @@ capture(setting: PhotoCaptureSetting, callback: AsyncCallback<void\>): void ...@@ -3253,7 +2228,7 @@ capture(setting: PhotoCaptureSetting, callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------- | ---- | -------------------- | | -------- | ------------------------------------------- | ---- | -------------------- |
| setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 | | setting | [PhotoCaptureSetting](#photocapturesetting) | 是 | 拍照设置。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
...@@ -3271,7 +2246,7 @@ let settings = { ...@@ -3271,7 +2246,7 @@ let settings = {
} }
photoOutput.capture(settings, (err) => { photoOutput.capture(settings, (err) => {
if (err) { if (err) {
console.error(`Failed to capture the photo ${err.message}`); console.error(`Failed to capture the photo ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate the photo capture request success.'); console.log('Callback invoked to indicate the photo capture request success.');
...@@ -3296,41 +2271,37 @@ capture(setting?: PhotoCaptureSetting): Promise<void\> ...@@ -3296,41 +2271,37 @@ capture(setting?: PhotoCaptureSetting): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
photoOutput.capture().then(() => { photoOutput.capture(settings).then(() => {
console.log('Promise returned to indicate that photo capture request success.'); console.log('Promise returned to indicate that photo capture request success.');
}) }).catch((err) => {
console.log('Failed to photoOutput capture '+ err.code);
});
``` ```
### isMirrorSupported ### isMirrorSupported
isMirrorSupported(callback: AsyncCallback<boolean\>): void isMirrorSupported(): boolean
查询是否支持镜像拍照,通过注册回调函数获取结果 查询是否支持镜像拍照。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:** **返回值:**
| 参数名 | 类型 | 必填 | 说明 | | 类型 | 说明 |
| -------- | ------------------------------------------------- | ---- | -------------------------- | | -------------- | ----------------------- |
| callback | AsyncCallback<boolean\> | 是 | 回调函数,返回是否支持镜像拍照。 | | boolean | 返回是否支持镜像拍照。 |
**示例:** **示例:**
```js ```js
photoOutput.isMirrorSupported((err, isSupported) => { let isSupported = photoOutput.isMirrorSupported();
if (err) {
console.error(`Failed to check mirror is supported ${err.message}`);
return;
}
console.log('Callback returned with the successful execution of isMirrorSupported.');
})
``` ```
### release ### release
...@@ -3345,14 +2316,14 @@ release(callback: AsyncCallback<void\>): void ...@@ -3345,14 +2316,14 @@ release(callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
photoOutput.release((err) => { photoOutput.release((err) => {
if (err) { if (err) {
console.error(`Failed to release the PreviewOutput instance ${err.message}`); console.error(`Failed to release the PreviewOutput instance ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
...@@ -3371,36 +2342,16 @@ release(): Promise<void\> ...@@ -3371,36 +2342,16 @@ release(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
photoOutput.release().then(() => { photoOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
}) }).catch((err) => {
``` console.log('Failed to photoOutput release '+ err.code);
});
### isMirrorSupported
isMirrorSupported(): Promise<boolean\>
查询是否支持镜像拍照,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:**
| 类型 | 说明 |
| ----------------- | ------------------------------------------- |
| Promise<boolean\> | 使用Promise的方式获取结果,返回是否支持自拍结果。 |
**示例:**
```js
photoOutput.isMirrorSupported().then((isSupported) => {
console.log(`Promise returned with mirror supported: ${isSupported}`);
})
``` ```
### on('captureStart') ### on('captureStart')
...@@ -3415,13 +2366,13 @@ on(type: 'captureStart', callback: AsyncCallback<number\>): void ...@@ -3415,13 +2366,13 @@ on(type: 'captureStart', callback: AsyncCallback<number\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------------------------------------ | | -------- | ---------------------- | ---- | ------------------------------------------ |
| type | string | 是 | 监听事件,固定为'captureStart',即拍照启动事件。 | | type | string | 是 | 监听事件,固定为'captureStart',callback返回拍照开始事件。 |
| callback | AsyncCallback<number\> | 是 | 使用callback的方式获取Capture ID。 | | callback | AsyncCallback<number\> | 是 | 使用callback的方式获取Capture ID。 |
**示例:** **示例:**
```js ```js
photoOutput.on('captureStart', (err, captureId) => { photoOutput.on('captureStart', (captureId) => {
console.log(`photo capture stated, captureId : ${captureId}`); console.log(`photo capture stated, captureId : ${captureId}`);
}) })
``` ```
...@@ -3438,13 +2389,13 @@ on(type: 'frameShutter', callback: AsyncCallback<FrameShutterInfo\>): void ...@@ -3438,13 +2389,13 @@ on(type: 'frameShutter', callback: AsyncCallback<FrameShutterInfo\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------- | --- | ------------------------------------ | | -------- | ----------------------------------------------------- | --- | ------------------------------------ |
| type | string | 是 | 监听事件,固定为'frameShutter',即帧刷新事件。 | | type | string | 是 | 监听事件,固定为'frameShutter',callback返回拍照图像获取成功信息(captureId跟获取时间)。 |
| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | 是 | 回调函数,用于获取相关信息。 | | callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | 是 | 回调函数,用于获取相关信息。 |
**示例:** **示例:**
```js ```js
photoOutput.on('frameShutter', (err, frameShutterInfo) => { photoOutput.on('frameShutter', (frameShutterInfo) => {
console.log(`photo capture end, captureId : ${frameShutterInfo.captureId}`); console.log(`photo capture end, captureId : ${frameShutterInfo.captureId}`);
console.log(`Timestamp for frame : ${frameShutterInfo.timestamp}`); console.log(`Timestamp for frame : ${frameShutterInfo.timestamp}`);
}) })
...@@ -3462,13 +2413,13 @@ on(type: 'captureEnd', callback: AsyncCallback<CaptureEndInfo\>): void ...@@ -3462,13 +2413,13 @@ on(type: 'captureEnd', callback: AsyncCallback<CaptureEndInfo\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------------------------------- | ---- | ---------------------------------------- |
| type | string | 是 | 监听事件,固定为'captureEnd',即拍照停止事件。 | | type | string | 是 | 监听事件,固定为'captureEnd',callback返回拍照结束事件。 |
| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | 是 | 回调函数,用于获取相关信息。 | | callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | 是 | 回调函数,用于获取相关信息。 |
**示例:** **示例:**
```js ```js
photoOutput.on('captureEnd', (err, captureEndInfo) => { photoOutput.on('captureEnd', (captureEndInfo) => {
console.log(`photo capture end, captureId : ${captureEndInfo.captureId}`); console.log(`photo capture end, captureId : ${captureEndInfo.captureId}`);
console.log(`frameCount : ${captureEndInfo.frameCount}`); console.log(`frameCount : ${captureEndInfo.frameCount}`);
}) })
...@@ -3476,7 +2427,7 @@ photoOutput.on('captureEnd', (err, captureEndInfo) => { ...@@ -3476,7 +2427,7 @@ photoOutput.on('captureEnd', (err, captureEndInfo) => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<PhotoOutputError\>): void on(type: 'error', callback: ErrorCallback<BusinessError\>): void
监听拍照输出发生错误,通过注册回调函数获取结果。 监听拍照输出发生错误,通过注册回调函数获取结果。
...@@ -3486,14 +2437,14 @@ on(type: 'error', callback: ErrorCallback<PhotoOutputError\>): void ...@@ -3486,14 +2437,14 @@ on(type: 'error', callback: ErrorCallback<PhotoOutputError\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------- | ---- | ----------------------------------- | | -------- | ----------------------------------------------------- | ---- | ----------------------------------- |
| type | string | 是 | 监听事件,固定为'error',即拍照错误事件。 | | type | string | 是 | 监听事件,固定为'error',callback 返回拍照接口调用时出现错误并返回错误码。 |
| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | | callback | ErrorCallback<BusinessError\> | 是 | 回调函数,用于获取错误信息。返回错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
photoOutput.on('error', (err, photoOutputError) => { photoOutput.on('error', (error) => {
console.log(`Photo output error code: ${photoOutputError.code}`); console.log(`Photo output error code: ${error.code}`);
}) })
``` ```
...@@ -3519,29 +2470,6 @@ photoOutput.on('error', (err, photoOutputError) => { ...@@ -3519,29 +2470,6 @@ photoOutput.on('error', (err, photoOutputError) => {
| captureId | number | 是 | 拍照的ID。 | | captureId | number | 是 | 拍照的ID。 |
| frameCount | number | 是 | 帧数。 | | frameCount | number | 是 | 帧数。 |
## PhotoOutputErrorCode
枚举,拍照输出错误类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 |
| ----------------------------- | ---- | --------------- |
| ERROR_UNKNOWN | -1 | 未知错误。 |
| ERROR_DRIVER_ERROR | 0 | 驱动或者硬件错误。 |
| ERROR_INSUFFICIENT_RESOURCES | 1 | 资源不足。 |
| ERROR_TIMEOUT | 2 | 超时。 |
## PhotoOutputError
拍照输出错误码。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 类型 | 必填 |说明 |
| ---- | ------------------------------------- | --------- | ----------------------- |
| code | [PhotoOutputErrorCode](#photooutputerrorcode) | 是 | PhotoOutput中的错误码。 |
## VideoOutput ## VideoOutput
录像会话中使用的输出信息,继承[CameraOutput](#cameraoutput) 录像会话中使用的输出信息,继承[CameraOutput](#cameraoutput)
...@@ -3558,14 +2486,14 @@ start(callback: AsyncCallback<void\>): void ...@@ -3558,14 +2486,14 @@ start(callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
videoOutput.start((err) => { videoOutput.start((err) => {
if (err) { if (err) {
console.error(`Failed to start the video output ${err.message}`); console.error(`Failed to start the video output ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate the video output start success.'); console.log('Callback invoked to indicate the video output start success.');
...@@ -3584,7 +2512,7 @@ start(): Promise<void\> ...@@ -3584,7 +2512,7 @@ start(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
...@@ -3592,7 +2520,9 @@ start(): Promise<void\> ...@@ -3592,7 +2520,9 @@ start(): Promise<void\>
```js ```js
videoOutput.start().then(() => { videoOutput.start().then(() => {
console.log('Promise returned to indicate that start method execution success.'); console.log('Promise returned to indicate that start method execution success.');
}) }).catch((err) => {
console.log('Failed to videoOutput start '+ err.code);
});
``` ```
### stop ### stop
...@@ -3614,7 +2544,7 @@ stop(callback: AsyncCallback<void\>): void ...@@ -3614,7 +2544,7 @@ stop(callback: AsyncCallback<void\>): void
```js ```js
videoOutput.stop((err) => { videoOutput.stop((err) => {
if (err) { if (err) {
console.error(`Failed to stop the video output ${err.message}`); console.error(`Failed to stop the video output ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate the video output stop success.'); console.log('Callback invoked to indicate the video output stop success.');
...@@ -3640,8 +2570,10 @@ stop(): Promise<void\> ...@@ -3640,8 +2570,10 @@ stop(): Promise<void\>
```js ```js
videoOutput.stop().then(() => { videoOutput.stop().then(() => {
console.log('Promise returned to indicate that stop method execution success.'); console.log('Promise returned to indicate that stop method execution success.');
}) }).catch((err) => {
``` console.log('Failed to videoOutput stop '+ err.code);
});
```
### release ### release
...@@ -3655,14 +2587,14 @@ release(callback: AsyncCallback<void\>): void ...@@ -3655,14 +2587,14 @@ release(callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
videoOutput.release((err) => { videoOutput.release((err) => {
if (err) { if (err) {
console.error(`Failed to release the PreviewOutput instance ${err.message}`); console.error(`Failed to release the PreviewOutput instance ${err.code}`);
return; return;
} }
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
...@@ -3681,14 +2613,16 @@ release(): Promise<void\> ...@@ -3681,14 +2613,16 @@ release(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
videoOutput.release().then(() => { videoOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
}) }).catch((err) => {
console.log('Failed to videoOutput release '+ err.code);
});
``` ```
### on('frameStart') ### on('frameStart')
...@@ -3703,7 +2637,7 @@ on(type: 'frameStart', callback: AsyncCallback<void\>): void ...@@ -3703,7 +2637,7 @@ on(type: 'frameStart', callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ----------------------------------------- | | -------- | -------------------- | ---- | ----------------------------------------- |
| type | string | 是 | 监听事件,固定为'frameStart',即视频帧开启事件。 | | type | string | 是 | 监听事件,固定为'frameStart',callback返回录像开始获取第一帧图像时返回。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
...@@ -3726,7 +2660,7 @@ on(type: 'frameEnd', callback: AsyncCallback<void\>): void ...@@ -3726,7 +2660,7 @@ on(type: 'frameEnd', callback: AsyncCallback<void\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------------------------------ | | -------- | -------------------- | ---- | ------------------------------------------ |
| type | string | 是 | 监听事件,固定为'frameEnd',即视频帧结束事件 。 | | type | string | 是 | 监听事件,固定为'frameEnd',callback返回录像结束获取最后一帧图像时返回 。 |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 |
**示例:** **示例:**
...@@ -3739,7 +2673,7 @@ videoOutput.on('frameEnd', () => { ...@@ -3739,7 +2673,7 @@ videoOutput.on('frameEnd', () => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<VideoOutputError\>): void on(type: 'error', callback: ErrorCallback<BusinessError\>): void
监听录像输出发生错误,通过注册回调函数获取结果。 监听录像输出发生错误,通过注册回调函数获取结果。
...@@ -3749,38 +2683,17 @@ on(type: 'error', callback: ErrorCallback<VideoOutputError\>): void ...@@ -3749,38 +2683,17 @@ on(type: 'error', callback: ErrorCallback<VideoOutputError\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------ | ---- | -------------------------------------- | | -------- | ------------------------------------------------ | ---- | -------------------------------------- |
| type | string | 是 | 监听事件,固定为'error',即视频输出错误事件。 | | type | string | 是 | 监听事件,固定为'error',callback返回录像接口调用时出现错误时返回对应错误码,比如调用(start(),release())接口时出现错误返回对应错误码。 |
| callback | Callback<[VideoOutputError](#videooutputerror)\> | 是 | 回调函数,用于获取错误信息。 | | callback | Callback<BusinessError\> | 是 | 回调函数,用于获取错误信息。返回错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
videoOutput.on('error', (VideoOutputError) => { videoOutput.on('error', (error) => {
console.log(`Video output error code: ${VideoOutputError.code}`); console.log(`Video output error code: ${error.code}`);
}) })
``` ```
## VideoOutputErrorCode
枚举,录像输出错误类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 |
| --------------------- | ---- | ------------ |
| ERROR_UNKNOWN | -1 | 未知错误。 |
| ERROR_DRIVER_ERROR | 0 | 驱动或者硬件错误。|
## VideoOutputError
录像输出错误码。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 类型 | 必填 | 说明 |
| ---- | ------------------------------------- | ----------------- | ----------------------- |
| code | [PhotoOutputErrorCode](#photooutputerrorcode) | 是 | VideoOutput中的错误码。 |
## MetadataOutput ## MetadataOutput
metadata流。继承[CameraOutput](#cameraoutput) metadata流。继承[CameraOutput](#cameraoutput)
...@@ -3796,15 +2709,15 @@ start(callback: AsyncCallback<void\>): void ...@@ -3796,15 +2709,15 @@ start(callback: AsyncCallback<void\>): void
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ------------------- | | -------- | -------------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。 | | callback | AsyncCallback<void\> | 是 | 回调函数,用于获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
metadataOutput.start((err) => { metadataOutput.start((err) => {
if (err) { if (err) {
console.error(`Failed to start metadataOutput. ${err.message}`); console.error(`Failed to start metadataOutput. ${err.code}`);
return; return;
} }
console.log('Callback returned with metadataOutput started.'); console.log('Callback returned with metadataOutput started.');
...@@ -3823,14 +2736,16 @@ start(): Promise<void\> ...@@ -3823,14 +2736,16 @@ start(): Promise<void\>
| 类型 | 说明 | | 类型 | 说明 |
| ---------------------- | ------------------------ | | ---------------------- | ------------------------ |
| Promise<void\> | 使用Promise的方式获取结果。 | | Promise<void\> | 使用Promise的方式获取结果。接口调用失败会返回相应错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
```js ```js
metadataOutput.start().then(() => { metadataOutput.start().then(() => {
console.log('Callback returned with metadataOutput started.'); console.log('Callback returned with metadataOutput started.');
}) }).catch((err) => {
console.log('Failed to metadataOutput start '+ err.code);
});
``` ```
### stop ### stop
...@@ -3852,7 +2767,7 @@ stop(callback: AsyncCallback<void\>): void ...@@ -3852,7 +2767,7 @@ stop(callback: AsyncCallback<void\>): void
```js ```js
metadataOutput.stop((err) => { metadataOutput.stop((err) => {
if (err) { if (err) {
console.error(`Failed to stop the metadataOutput. ${err.message}`); console.error(`Failed to stop the metadataOutput. ${err.code}`);
return; return;
} }
console.log('Callback returned with metadataOutput stopped.'); console.log('Callback returned with metadataOutput stopped.');
...@@ -3878,7 +2793,9 @@ stop(): Promise<void\> ...@@ -3878,7 +2793,9 @@ stop(): Promise<void\>
```js ```js
metadataOutput.stop().then(() => { metadataOutput.stop().then(() => {
console.log('Callback returned with metadataOutput stopped.'); console.log('Callback returned with metadataOutput stopped.');
}) }).catch((err) => {
console.log('Failed to metadataOutput stop '+ err.code);
});
``` ```
### on('metadataObjectsAvailable') ### on('metadataObjectsAvailable')
...@@ -3893,8 +2810,8 @@ on(type: 'metadataObjectsAvailable', callback: AsyncCallback<Array<MetadataObjec ...@@ -3893,8 +2810,8 @@ on(type: 'metadataObjectsAvailable', callback: AsyncCallback<Array<MetadataObjec
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------ | ---- | ------------------------------------ | | -------- | ------------------------------------------------ | ---- | ------------------------------------ |
| type | string | 是 | 监听事件,固定为'metadataObjectsAvailable',即metadata对象。 | | type | string | 是 | 监听事件,固定为'metadataObjectsAvailable',检测到有效的metadata数据时callback返回相应的metadata数据,metadataOutput创建成功时可监听。 |
| callback | Callback<Array<[MetadataObject](#metadataobject)\>\> | 是 | 回调函数,用于获取错误信息。 | | callback | Callback<Array<[MetadataObject](#metadataobject)\>\> | 是 | 回调函数,用于获取metadata数据。 |
**示例:** **示例:**
...@@ -3906,7 +2823,7 @@ metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => { ...@@ -3906,7 +2823,7 @@ metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<MetadataOutputError\>): void on(type: 'error', callback: ErrorCallback<BusinessError\>): void
监听metadata流的错误,通过注册回调函数获取结果。 监听metadata流的错误,通过注册回调函数获取结果。
...@@ -3916,8 +2833,8 @@ on(type: 'error', callback: ErrorCallback<MetadataOutputError\>): void ...@@ -3916,8 +2833,8 @@ on(type: 'error', callback: ErrorCallback<MetadataOutputError\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------ | ---- | --------------------------------------- | | -------- | ------------------------------------------------ | ---- | --------------------------------------- |
| type | string | 是 | 监听事件,固定为'error',即metadata流的错误。 | | type | string | 是 | 监听事件,固定为'error',callback 返回metadata输出接口使用错误时返回对应错误码,比如调用(start(),release())接口时发生错误返回对应错误码。 |
| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | 是 | 回调函数,用于获取错误信息。 | | callback | Callback<BusinessError\> | 是 | 回调函数,用于获取错误信息。返回错误码,错误码类型[CameraErrorCode](#cameraerrorcode) |
**示例:** **示例:**
...@@ -3927,27 +2844,6 @@ metadataOutput.on('error', (metadataOutputError) => { ...@@ -3927,27 +2844,6 @@ metadataOutput.on('error', (metadataOutputError) => {
}) })
``` ```
## MetadataOutputErrorCode
枚举,metadata输出错误类型。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 值 | 说明 |
| ------------------------------- | ---- | -------- |
| ERROR_UNKNOWN | -1 | 未知错误。 |
| ERROR_INSUFFICIENT_RESOURCES | 0 | 资源不足。 |
## MetadataOutputError
metadata输出错误码。
**系统能力:** SystemCapability.Multimedia.Camera.Core
| 名称 | 类型 | 必填 | 说明 |
| ---- | ------------------------------------- | ----------------- | ----------------------- |
| code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | 是 | MetadataOutput中的错误码。 |
## MetadataObjectType ## MetadataObjectType
枚举,metadata流。 枚举,metadata流。
...@@ -3956,7 +2852,7 @@ metadata输出错误码。 ...@@ -3956,7 +2852,7 @@ metadata输出错误码。
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| ------------------------- | ---- | ----------------- | | ------------------------- | ---- | ----------------- |
| FACE_DETECTION | 0 | metadata对象类型。 | | FACE_DETECTION | 0 | metadata对象类型,人脸检测。 |
## Rect ## Rect
...@@ -3975,156 +2871,8 @@ metadata输出错误码。 ...@@ -3975,156 +2871,8 @@ metadata输出错误码。
相机元能力信息,[CameraInput](#camerainput)相机信息中的数据来源,通过metadataOutput.on('metadataObjectsAvailable')接口获取 相机元能力信息,[CameraInput](#camerainput)相机信息中的数据来源,通过metadataOutput.on('metadataObjectsAvailable')接口获取
### getType | 名称 | 类型 | 必填 | 说明 |
| -------- | ------------------------------- | ---- | -----------------|
getType(callback: AsyncCallback<MetadataObjectType\>): void | type | [MetadataObjectType](#metadataobjecttype) | 否 | metadata 类型,目前只有人脸识别。 |
| timestamp | number | 否 | 当前时间戳(毫秒)。 |
查询metadata对象类型,通过注册回调函数获取结果。 | boundingBox | [Rect](#rect) | 否 | metadata 区域框 |
\ No newline at end of file
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------------------- | --- | -------------------- |
| callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
let metadataObject = metadataObjectArr[0];
metadataObject.getType((err, metadataObjectType) => {
if (err) {
console.error(`Failed to get type. ${err.message}`);
return;
}
console.log('Callback returned with an array of metadataObjectType.');
})
```
### getType
getType(): Promise<MetadataObjectType\>
查询metadata对象类型,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:**
| 类型 | 说明 |
| --------------------------------------------------- | --------------------------- |
| Promise<[MetadataObjectType](#metadataobjecttype)\> | 使用Promise的方式获取结果。 |
**示例:**
```js
let metadataObject = metadataObjectArr[0];
metadataObject.getType().then((metadataObjectType) => {
console.log('Callback returned with an array of metadataObjectType.');
})
```
### getTimestamp
getTimestamp(callback: AsyncCallback<number\>): void
查询metadata时间戳,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ------------------------ |
| callback | AsyncCallback<number\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
let metadataObject = metadataObjectArr[0];
metadataObject.getTimestamp((err,timestamp) => {
if (err) {
console.error(`Failed to get timestamp. ${err.message}`);
return;
}
console.log('Callback returned with timestamp getted timestamp : ${timestamp}');
})
```
### getTimestamp
getTimestamp(): Promise<number\>
查询metadata时间戳,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:**
| 类型 | 说明 |
| ---------------- | --------------------------- |
| Promise<number)\> | 使用Promise的方式获取结果。 |
**示例:**
```js
let metadataObject = metadataObjectArr[0];
metadataObject.getTimestamp().then((timestamp) => {
console.log('Callback returned with timestamp getted timestamp : ${timestamp}');
})
```
### getBoundingBox
getBoundingBox(callback: AsyncCallback<Rect\>): void
查询metadata的边界框,通过注册回调函数获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ------------------------ |
| callback | AsyncCallback<[Rect](#rect)\> | 是 | 回调函数,用于获取结果。 |
**示例:**
```js
let metadataObject = metadataObjectArr[0];
metadataObject.getBoundingBox((err, rect) => {
if (err) {
console.error(`Failed to get boundingBox. ${err.message}`);
return;
}
console.log('Callback returned with boundingBox getted.');
})
```
### getBoundingBox
getBoundingBox(): Promise<Rect\>
查询metadata的边界框,通过Promise获取结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core
**返回值:**
| 类型 | 说明 |
| ---------------------- | --------------------------- |
| Promise<[Rect](#rect)\> | 使用Promise的方式获取结果。 |
**示例:**
```js
let metadataObject = metadataObjectArr[0];
metadataObject.getBoundingBox().then((rect) => {
console.log('Callback returned with boundingBox getted.');
})
```
## MetadataFaceObject
metadata的人脸对象。继承[MetadataObject](#metadataobject)
\ No newline at end of file
...@@ -121,7 +121,7 @@ createDeviceManager(bundleName: string, callback: AsyncCallback&lt;DeviceManager ...@@ -121,7 +121,7 @@ createDeviceManager(bundleName: string, callback: AsyncCallback&lt;DeviceManager
| mode | [DiscoverMode ](#discovermode) | 否 | 发现模式。 | | mode | [DiscoverMode ](#discovermode) | 否 | 发现模式。 |
| medium | [ExchangeMedium](#exchangemedium) | 否 | 发现类型。 | | medium | [ExchangeMedium](#exchangemedium) | 否 | 发现类型。 |
| freq | [ExchangeFreq](#exchangefreq) | 否 | 发现频率。 | | freq | [ExchangeFreq](#exchangefreq) | 否 | 发现频率。 |
| isSameAccount | boolean | 否 | 是否同号。 | | isSameAccount | boolean | 否 | 是否同号。 |
| isWakeRemote | boolean | 否 | 是否唤醒设备。 | | isWakeRemote | boolean | 否 | 是否唤醒设备。 |
| capability | [SubscribeCap](#subscribecap) | 否 | 发现能力。 | | capability | [SubscribeCap](#subscribecap) | 否 | 发现能力。 |
...@@ -711,7 +711,7 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async ...@@ -711,7 +711,7 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async
deviceType: 0x0E deviceType: 0x0E
}; };
let authParam = { let authParam = {
"authType": 1, // 认证类型: 1 - 无号PIN码认证 "authType": 1, // 认证类型: 1 - 无号PIN码认证
"extraInfo": {} "extraInfo": {}
} }
try { try {
......
...@@ -755,7 +755,7 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -755,7 +755,7 @@ remove(callback: AsyncCallback&lt;boolean&gt;): void
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| filename | string | 是 | multipart提交时,请求头中的文件名。 | | filename | string | 是 | multipart提交时,请求头中的文件名。 |
| name | string | 是 | multipart提交时,表单项目的名称,缺省为file。 | | 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 | 是 | 文件的内容类型,默认根据文件名或路径的后缀获取。 | | type | string | 是 | 文件的内容类型,默认根据文件名或路径的后缀获取。 |
......
...@@ -66,8 +66,8 @@ requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): DelaySuspen ...@@ -66,8 +66,8 @@ requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): DelaySuspen
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspension delay will time out."); console.info("Request suspension delay will time out.");
}) })
var id = delayInfo.requestId; let id = delayInfo.requestId;
var time = delayInfo.actualDelayTime; let time = delayInfo.actualDelayTime;
console.info("The requestId is: " + id); console.info("The requestId is: " + id);
console.info("The actualDelayTime is: " + time); console.info("The actualDelayTime is: " + time);
} catch (error) { } catch (error) {
...@@ -281,14 +281,18 @@ export default class EntryAbility extends UIAbility { ...@@ -281,14 +281,18 @@ export default class EntryAbility extends UIAbility {
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}; };
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { try {
try { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
backgroundTaskManager.startBackgroundRunning(this.context, try {
backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) backgroundTaskManager.startBackgroundRunning(this.context,
} catch (error) { backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
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}`);
}
} }
}; };
``` ```
...@@ -352,18 +356,22 @@ export default class EntryAbility extends UIAbility { ...@@ -352,18 +356,22 @@ export default class EntryAbility extends UIAbility {
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}; };
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { try {
try { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
backgroundTaskManager.startBackgroundRunning(this.context, try {
backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { backgroundTaskManager.startBackgroundRunning(this.context,
console.info("Operation startBackgroundRunning succeeded"); backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
}).catch((error) => { 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}`); 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 ...@@ -89,11 +89,11 @@ upload(options: UploadRequestOptions): void
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。 **系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。
| 名称 | 类型 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| code | number | 服务器返回的HTTP状态码。 | | code | number | 是 | 服务器返回的HTTP状态码。 |
| data | string | 服务器返回的内容。根据返回头内容中的type决定该值的类型。 | | data | string | 是 | 服务器返回的内容。根据返回头内容中的type决定该值的类型。 |
| headers | Object | 服务器返回的返回头内容。 | | headers | Object | 是 | 服务器返回的返回头内容。 |
## RequestFile ## RequestFile
...@@ -189,9 +189,9 @@ download(options: DownloadRequestOptions): void ...@@ -189,9 +189,9 @@ download(options: DownloadRequestOptions): void
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。 **系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。
| 名称 | 类型 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| token | string | 表示下载的token,获取下载状态的依据。 | | token | string | 是 | 表示下载的token,获取下载状态的依据。 |
## request.onDownloadComplete ## request.onDownloadComplete
...@@ -254,6 +254,6 @@ onDownloadComplete(options: OnDownloadCompleteOptions): void ...@@ -254,6 +254,6 @@ onDownloadComplete(options: OnDownloadCompleteOptions): void
**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。 **系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download。
| 名称 | 类型 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| uri | string | 表示下载文件的uri。 | | uri | string | 是 | 表示下载文件的uri。 |
\ No newline at end of file \ No newline at end of file
...@@ -1864,7 +1864,7 @@ getWindowAvoidArea(type: AvoidAreaType): AvoidArea ...@@ -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 ...@@ -2500,7 +2500,7 @@ off(type: 'windowSizeChange', callback?: Callback&lt;Size&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------- | ---- | -------------------------------------------------------- | | -------- | ----------------------------- | ---- | -------------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'windowSizeChange',即窗口尺寸变化事件。 | | 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;): ...@@ -3006,7 +3006,7 @@ setWindowColorSpace(colorSpace:ColorSpace, callback: AsyncCallback&lt;void&gt;):
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------- | -- | ----------- | | ---------- | ------------------------- | -- | ----------- |
| colorSpace | [ColorSpace](#colorspace) | 是 | 设置色域模式。 | | colorSpace | [ColorSpace](#colorspace8) | 是 | 设置色域模式。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**错误码:** **错误码:**
...@@ -3045,7 +3045,7 @@ setWindowColorSpace(colorSpace:ColorSpace): Promise&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 ...@@ -3088,7 +3088,7 @@ getWindowColorSpace(): ColorSpace
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------- | ------------- | | ------------------------- | ------------- |
| [ColorSpace](#colorspace) | 当前色域模式。 | | [ColorSpace](#colorspace8) | 当前色域模式。 |
**错误码:** **错误码:**
...@@ -4615,7 +4615,7 @@ getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback&lt; ...@@ -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; | 是 | 回调函数。返回窗口内容规避区域。 | | callback | AsyncCallback&lt;[AvoidArea](#avoidarea7)&gt; | 是 | 回调函数。返回窗口内容规避区域。 |
**示例:** **示例:**
...@@ -4647,7 +4647,7 @@ getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise&lt;[AvoidArea](#av ...@@ -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 ...@@ -5205,7 +5205,7 @@ setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------- | ---- | ------------ | | ---------- | ------------------------- | ---- | ------------ |
| colorSpace | [ColorSpace](#colorspace) | 是 | 设置色域模式。 | | colorSpace | [ColorSpace](#colorspace8) | 是 | 设置色域模式。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:** **示例:**
...@@ -5236,7 +5236,7 @@ setColorSpace(colorSpace:ColorSpace): Promise&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 ...@@ -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; ...@@ -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 ...@@ -3261,7 +3261,7 @@ confirm(userName: string, pwd: string): boolean
isHttpAuthInfoSaved(): boolean isHttpAuthInfoSaved(): boolean
通知Web组件用户使用服务器缓存的号密码认证。 通知Web组件用户使用服务器缓存的号密码认证。
**返回值:** **返回值:**
......
...@@ -200,7 +200,7 @@ focusControl.requestFocus示例代码: ...@@ -200,7 +200,7 @@ focusControl.requestFocus示例代码:
使用focusContrl.requestFocus接口使指定组件获取焦点。 使用focusContrl.requestFocus接口使指定组件获取焦点。
```ts ```ts
// requestFocus.ets // requestFocus.ets
import prompt from '@ohos.prompt' import promptAction from '@ohos.promptAction';
@Entry @Entry
@Component @Component
...@@ -252,9 +252,9 @@ struct RequestFocusExample { ...@@ -252,9 +252,9 @@ struct RequestFocusExample {
.onClick(() => { .onClick(() => {
var res = focusControl.requestFocus(this.selectId) // 使选中的this.selectId的组件获焦 var res = focusControl.requestFocus(this.selectId) // 使选中的this.selectId的组件获焦
if (res) { if (res) {
prompt.showToast({message: 'Request success'}) promptAction.showToast({message: 'Request success'})
} else { } else {
prompt.showToast({message: 'Request failed'}) promptAction.showToast({message: 'Request failed'})
} }
}) })
} }
......
...@@ -989,7 +989,7 @@ TS/JS语言基础库 ...@@ -989,7 +989,7 @@ TS/JS语言基础库
## SystemCapability.Account.AppAccount ## SystemCapability.Account.AppAccount
应用 应用
| Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router | | Default | 运动表 | 智能表 | 平板 | 车机 | 智慧屏 | Smart-Vision | Router |
| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | | ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ |
......
...@@ -246,7 +246,7 @@ ...@@ -246,7 +246,7 @@
## ohos.permission.MANAGE_LOCAL_ACCOUNTS ## ohos.permission.MANAGE_LOCAL_ACCOUNTS
允许应用管理本地用户号。 允许应用管理本地用户号。
**权限级别**:system_basic **权限级别**:system_basic
...@@ -256,7 +256,7 @@ ...@@ -256,7 +256,7 @@
## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS ## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
允许多个系统号之间相互访问。 允许多个系统号之间相互访问。
**权限级别**:system_basic **权限级别**:system_basic
......
...@@ -100,13 +100,13 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业 ...@@ -100,13 +100,13 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业
- 携带参数信息支持number、string、bool三种类型。 - 携带参数信息支持number、string、bool三种类型。
## 申请能效资源 ## 申请能效资源
能效资源可以分为四种:CPU资源,WORK_SCHEDULER资源,软件资源(COMMON_EVENT,TIMER),硬件资源(GPS,BLUETOOTH,AUDIO)。 供系统应用使用的能效资源可以分为两类:软件资源(WORK_SCHEDULER, COMMON_EVENT, TIMER),硬件资源(CPU, GPS, BLUETOOTH, AUDIO)。
应用或进程申请能效资源后能够获得相应特权 应用申请不同的能效资源后可以执行相应的操作
* 申请CPU资源后可以不被挂起,直到任务完成。 * 申请CPU资源后可以不被挂起,直到任务完成。
* 申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加 * 申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加
* 申请COMMON_EVENT资源后,应用在后台处于挂起状态时,仍然能够接收到系统公共事件,申请TIMER资源后,应用能够使用定时器执行精确定时任务 * 申请COMMON_EVENT资源后,应用在后台处于挂起状态时,仍然能够接收到系统公共事件,申请TIMER资源后,应用能够使用定时器执行精确定时任务
* 申请硬件资源后,应用在后台被挂起后,依然能够被相关服务唤醒,执行相应的任务。 * 申请资源(GPS, BLUETOOTH, AUDIO)后,应用在后台被挂起后,依然能够被管理相关硬件的服务唤醒,执行相应的任务。
**表1** 能效资源种类 **表1** 能效资源种类
...@@ -125,4 +125,4 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业 ...@@ -125,4 +125,4 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业
- 能效资源申请或者释放可以由进程或者应用发起,由应用发起的资源释放会释放属于它的同类型的所有资源,包括进程申请的资源。例如应用申请了CPU资源,进程申请了CPU和WORK_SCHEDULER资源,当应用释放CPU资源的时候,会将进程的CPU资源一同释放,同时不同类型的WORK_SCHEDULER资源不受影响。由进程发起的资源释放对应用申请的资源没有影响,例如当应用和进程同时申请了CPU,进程发起了CPU资源释放,应用的CPU资源不会被释放。 - 能效资源申请或者释放可以由进程或者应用发起,由应用发起的资源释放会释放属于它的同类型的所有资源,包括进程申请的资源。例如应用申请了CPU资源,进程申请了CPU和WORK_SCHEDULER资源,当应用释放CPU资源的时候,会将进程的CPU资源一同释放,同时不同类型的WORK_SCHEDULER资源不受影响。由进程发起的资源释放对应用申请的资源没有影响,例如当应用和进程同时申请了CPU,进程发起了CPU资源释放,应用的CPU资源不会被释放。
- 同时申请同一类持久资源和非持久资源,持久资源会覆盖非持久资源,在超时时不会释放资源。例如应用首先申请了10s的CPU资源,然后在第5s的时候申请了持久的CPU资源,那么资源会变成持久的,非持久的CPU资源记录会被持久化的CPU资源记录覆盖,到了第10s的时候资源不会被释放,如果在第8s的时候提前释放了资源,那么会将CPU资源释放,无法单独释放其中非持久的或者持久的CPU资源。 - 同时申请同一类持久资源和非持久资源,持久资源会覆盖非持久资源,在超时时不会释放资源。例如应用首先申请了10s的CPU资源,然后在第5s的时候申请了持久的CPU资源,那么资源会变成持久的,非持久的CPU资源记录会被持久化的CPU资源记录覆盖,到了第10s的时候资源不会被释放,如果在第8s的时候提前释放了资源,那么会将CPU资源释放,无法单独释放其中非持久的或者持久的CPU资源。
- WORK_SCHEDULER资源只能由应用申请和释放,不能由进程申请和释放。 - WORK_SCHEDULER资源只能由应用申请和释放,不能由进程申请和释放。
- 需要使用能效资源的应用,需要向应用中心提出申请,获取相应的特权。 - 需要使用能效资源的应用必须是系统应用,同时需要向应用中心提出申请,配置相应的特权。
...@@ -89,18 +89,22 @@ struct Index { ...@@ -89,18 +89,22 @@ struct Index {
}; };
// 通过wantAgent模块的getWantAgent方法获取WantAgent对象 // 通过wantAgent模块的getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { try {
try { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
backgroundTaskManager.startBackgroundRunning(this.context, try {
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { backgroundTaskManager.startBackgroundRunning(this.context,
console.info("Operation startBackgroundRunning succeeded"); backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
}).catch((err) => { console.info("Operation startBackgroundRunning succeeded");
console.error("Operation startBackgroundRunning failed Cause: " + err); }).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 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() { stopContinuousTask() {
...@@ -151,7 +155,7 @@ struct Index { ...@@ -151,7 +155,7 @@ struct Index {
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; 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'; import wantAgent from '@ohos.app.ability.wantAgent';
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
...@@ -176,25 +180,29 @@ function startContinuousTask() { ...@@ -176,25 +180,29 @@ function startContinuousTask() {
}; };
// 通过wantAgent模块的getWantAgent方法获取WantAgent对象 // 通过wantAgent模块的getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { try {
try { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), try {
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { backgroundTaskManager.startBackgroundRunning(mContext,
console.info("Operation startBackgroundRunning succeeded"); backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
}).catch((error) => { 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}`); 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() { function stopContinuousTask() {
try { try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info("Operation stopBackgroundRunning succeeded"); console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => { }).catch((error) => {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`); console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}); });
} catch (error) { } catch (error) {
...@@ -312,7 +320,7 @@ export default class BgTaskAbility extends UIAbility { ...@@ -312,7 +320,7 @@ export default class BgTaskAbility extends UIAbility {
2、在Service Ability调用长时任务的申请和取消接口。 2、在Service Ability调用长时任务的申请和取消接口。
```js ```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
...@@ -335,18 +343,22 @@ function startContinuousTask() { ...@@ -335,18 +343,22 @@ function startContinuousTask() {
}; };
// 通过wantAgent模块的getWantAgent方法获取WantAgent对象 // 通过wantAgent模块的getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { try {
try { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), try {
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
console.info("Operation startBackgroundRunning succeeded"); backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
}).catch((err) => { console.info("Operation startBackgroundRunning succeeded");
console.error("Operation startBackgroundRunning failed Cause: " + err); }).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 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() { function stopContinuousTask() {
...@@ -396,7 +408,7 @@ class MyStub extends rpc.RemoteObject { ...@@ -396,7 +408,7 @@ class MyStub extends rpc.RemoteObject {
} }
export default { export default {
onStart(want) { onStart() {
console.info('ServiceAbility onStart'); console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test"); mMyStub = new MyStub("ServiceAbility-test");
// 在执行后台长时任前,调用申请接口。 // 在执行后台长时任前,调用申请接口。
...@@ -416,7 +428,7 @@ export default { ...@@ -416,7 +428,7 @@ export default {
onDisconnect() { onDisconnect() {
console.info('ServiceAbility onDisconnect'); console.info('ServiceAbility onDisconnect');
}, },
onCommand(want, restart, startId) { onCommand(want, startId) {
console.info('ServiceAbility onCommand'); console.info('ServiceAbility onCommand');
} }
}; };
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
2、当资源使用完毕,需要及时释放。支持释放部分资源或全部资源。 2、当资源使用完毕,需要及时释放。支持释放部分资源或全部资源。
```js ```js
import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
// 申请能效资源 // 申请能效资源
let request = { let request = {
...@@ -35,8 +35,14 @@ let request = { ...@@ -35,8 +35,14 @@ let request = {
isPersist: true, isPersist: true,
isProcess: 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 = { request = {
...@@ -44,10 +50,20 @@ request = { ...@@ -44,10 +50,20 @@ request = {
isApply: false, isApply: false,
timeOut: 0, timeOut: 0,
reason: "reset", reason: "reset",
isPersist: true,
isProcess: true,
}; };
res = backgroundTaskManager.applyEfficiencyResources(request); try {
console.info("the result of request is: " + res); 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介绍详见 ...@@ -43,7 +43,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
导入模块。 导入模块。
```ts ```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
``` ```
实现WorkSchedulerExtension生命周期接口。 实现WorkSchedulerExtension生命周期接口。
...@@ -52,27 +52,27 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 ...@@ -52,27 +52,27 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
export default class workAbility extends WorkSchedulerExtensionAbility { export default class workAbility extends WorkSchedulerExtensionAbility {
// 延迟任务开始回调 // 延迟任务开始回调
onWorkStart(workInfo) { 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) => { notification.publish(notificationRequest, (err) => {
if (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) { onWorkStop(workInfo) {
// 发送升级完成通知 // 发送升级完成通知
let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '') let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '');
notification.publish(notificationRequest, (err) => { notification.publish(notificationRequest, (err) => {
if (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介绍详见 ...@@ -91,13 +91,13 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
```ts ```ts
export default class WorkTest extends workAbility { export default class WorkTest extends workAbility {
onWorkStart(workInfo) { onWorkStart(workInfo) {
console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`) console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`);
super.onWorkStart(workInfo) super.onWorkStart(workInfo);
} }
onWorkStopTest(workInfo) { onWorkStopTest(workInfo) {
super.onWorkStop(workInfo) super.onWorkStop(workInfo);
console.log(`onWorkStop value`) console.log(`onWorkStop value`);
} }
} }
``` ```
...@@ -109,7 +109,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 ...@@ -109,7 +109,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
导入模块。 导入模块。
```ts ```ts
import workScheduler from '@ohos.resourceschedule.workScheduler' import workScheduler from '@ohos.resourceschedule.workScheduler';
``` ```
封装延迟任务注册、停止接口。 封装延迟任务注册、停止接口。
...@@ -124,25 +124,25 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 ...@@ -124,25 +124,25 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
} }
// 注册延迟任务 // 注册延迟任务
startWork(bundleName: string, abilityName: string) { startWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName this.workInfo.abilityName = abilityName;
try { try {
workScheduler.startWork(this.workInfo) workScheduler.startWork(this.workInfo);
console.log(`startWork success`) console.log(`startWork success`);
} catch (error) { } 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({ prompt.showToast({
message: `${error.message}` message: `${error.message}`
}) });
} }
} }
// 停止延迟任务 // 停止延迟任务
stopWork(bundleName: string, abilityName: string) { stopWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName this.workInfo.abilityName = abilityName;
workScheduler.stopWork(this.workInfo, false) workScheduler.stopWork(this.workInfo, false);
console.log(`stopWork`) console.log(`stopWork`);
} }
} }
``` ```
...@@ -152,7 +152,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 ...@@ -152,7 +152,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
导入模块。 导入模块。
```ts ```ts
import { workAbility } from '@ohos/library' import { workAbility } from '@ohos/library';
``` ```
增加“升级”按钮,调用library封装的延迟任务注册接口,传入bundleName和abilityName,其中bilityName为WorkTest。 增加“升级”按钮,调用library封装的延迟任务注册接口,传入bundleName和abilityName,其中bilityName为WorkTest。
...@@ -163,15 +163,15 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见 ...@@ -163,15 +163,15 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
.height(40) .height(40)
.fontSize(30) .fontSize(30)
.onClick(() => { .onClick(() => {
this.work.startWork('ohos.samples.workscheduler', 'WorkTest') this.work.startWork('ohos.samples.workscheduler', 'WorkTest');
}) });
``` ```
在组件析构时,调用延迟任务停止接口。 在组件析构时,调用延迟任务停止接口。
```ts ```ts
aboutToDisappear() { aboutToDisappear() {
this.work.stopWork('ohos.samples.workscheduler', 'WorkTest') this.work.stopWork('ohos.samples.workscheduler', 'WorkTest');
} }
``` ```
......
...@@ -49,30 +49,30 @@ ...@@ -49,30 +49,30 @@
- 可以通过`window.createWindow`接口创建子窗口。 - 可以通过`window.createWindow`接口创建子窗口。
- 也可以通过`window.findWindow`接口来查找已经创建的窗口从而得到子窗口。 - 也可以通过`window.findWindow`接口来查找已经创建的窗口从而得到子窗口。
```js ```js
import window from '@ohos.window'; import window from '@ohos.window';
let windowClass = null; let windowClass = null;
// 方式一:创建子窗口。 // 方式一:创建子窗口。
let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP}; let config = {name: "subWindow", windowType: window.WindowType.TYPE_APP};
window.createWindow(config, (err, data) => { window.createWindow(config, (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in creating subWindow. Data: ' + JSON.stringify(data));
windowClass = data; windowClass = data;
}); });
// 方式二:查找得到子窗口。 // 方式二:查找得到子窗口。
window.findWindow("subWindow", (err, data) => { window.findWindow("subWindow", (err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err)); console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data)); console.info('Succeeded in finding subWindow. Data: ' + JSON.stringify(data));
windowClass = data; windowClass = data;
}); });
``` ```
2. 设置子窗口属性。 2. 设置子窗口属性。
......
# 公共基础库常见问题
## LiteOS-A内核(Hi3516、Hi3518平台)KV存储路径设置错误,导致KV存储运行失败
**现象描述**
LiteOS-A内核(Hi3516、Hi3518平台)直接调用KV存储提供的接口,各参数正常的情况下,编译可执行程序运行失败。
**可能原因**
直接运行编译出的可执行文件,没有将程序基于AbilityKit转换成应用,不能由BMS在应用安装时正确设置应用数据存储路径,导致KV存储运行失败。
**解决办法**
显示调用KV存储的UtilsSetEnv接口,设置数据存储路径。
```
UtilsSetEnv("/storage/com.example.kv");
```
# 公共基础库开发指导 # 公共基础类库开发指导
## 概述
公共基础类库存放OpenHarmony通用的基础组件。这些基础组件包括一些常用的C、C++、JS开发增强API,可被OpenHarmony各业务子系统及上层应用所使用。公共基础类库子系统包含如下代码仓库:
## 接口说明
**表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);
``` ```
/commonlibrary
**表2** KV存储接口说明 ├── c_utils # c/c++标准库之外方便开发者开发的基础工具库
├── ets_utils # js标准库之外的与语言强相关的基础库
| 接口名 | 描述 | └── utils_lite # lite上使用的工具函数,涉及c和js语言
| -------- | -------- |
| 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);
``` ```
各仓库提供的功能列表如下:
**c_utils**
- 文件、路径、字符串相关操作的能力增强接口;
- 读写锁、信号量、定时器、线程增强及线程池等接口;
- 安全数据容器、数据序列化等接口;
- 各子系统的错误码相关定义;
## 开发步骤 **ets_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内核平台使用:
1. 连接单板,运行bin路径下的os_dump加参数--help,查看os_dump使用指导。 - JS中URI、URL、xml相关操作接口;
- JS中字符编解码接口;
``` - JS中进程相关操作接口;
./bin/os_dump --help - JS中多线程能力;
```
2. os_dump加参数-l,查看当前系统有哪些模块支持获取属性。 **utils_lite**
```
./bin/os_dump -l
```
3. os_dump加参数syspara,查看当前系统属性。 - 标准文件相关操作HAL接口;
- 其它一些内部功能,如定时器等。
```
./bin/os_dump syspara
```
**图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> # 公共基础库<a name="ZH-CN_TOPIC_0000001092539399"></a>
- [简介](#section11660541593) - [概述](#section11660541593)
- [目录](#section17271017133915) - [相关文档](#section17271017133915)
- [相关仓](#section1249817110914) - [相关仓](#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** **c_utils**
...@@ -27,14 +34,8 @@ ...@@ -27,14 +34,8 @@
- 标准文件相关操作HAL接口; - 标准文件相关操作HAL接口;
- 其它一些内部功能,如定时器等。 - 其它一些内部功能,如定时器等。
## 目录<a name="section17271017133915"></a> ## 相关文档<a name="section17271017133915"></a>
[公共基础类库开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-utils-guide.md)
```
/commonlibrary
├── c_utils # c/c++标准库之外方便开发者开发的基础工具库
├── ets_utils # js标准库之外的与语言强相关的基础库
└── utils_lite # lite上使用的工具函数,涉及c和js语言
```
## 相关仓<a name="section1249817110914"></a> ## 相关仓<a name="section1249817110914"></a>
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
OpenHarmony3.2.10.3 相对 OpenHarmony3.2 Beta4 版本,媒体子系统 camera 部件 API 变更如下 OpenHarmony3.2.10.3 相对 OpenHarmony3.2 Beta4 版本,媒体子系统 camera 部件 API 变更如下
## cl.subsystemname.1 camera 接口变更 ## 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.
先完成此消息的编辑!
想要评论请 注册