提交 f8d939dd 编写于 作者: E ester.zhou 提交者: Gitee

Merge branch 'monthly_20230815' of gitee.com:openharmony/docs into M-0829

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
...@@ -48,21 +48,18 @@ On the widget page, the **postCardAction** API can be used to trigger a message ...@@ -48,21 +48,18 @@ On the widget page, the **postCardAction** API can be used to trigger a message
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
export default class EntryFormAbility extends FormExtensionAbility { export default class EntryFormAbility extends FormExtensionAbility {
onFormEvent(formId, message) { onFormEvent(formId: string, message: string) {
// Called when a specified message event defined by the form provider is triggered. // Called when a specified message event defined by the form provider is triggered.
console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`); console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);
let formData = { let formData = new Map<Object, string>();
'title':'Title Update.', // It matches the widget layout. formData.set('title', 'Title Update.'); // It matches the widget layout.
'detail':'Description update success.', // It matches the widget layout. formData.set('detail', 'Description update success.'); // It matches the widget layout.
};
let formInfo = formBindingData.createFormBindingData(formData) let formInfo = formBindingData.createFormBindingData(formData)
formProvider.updateForm(formId, formInfo).then((data) => { formProvider.updateForm(formId, formInfo).then((data) => {
console.info('FormAbility updateForm success.' + JSON.stringify(data)); console.info('FormAbility updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
}) })
} }
... ...
} }
``` ```
......
...@@ -779,7 +779,9 @@ interface Employee extends Identity, Contact {} ...@@ -779,7 +779,9 @@ interface Employee extends Identity, Contact {}
**Severity: error** **Severity: error**
ArkTS does not support the returning `this` type. Use explicit type instead. ArkTS does not support type notation using the `this` keyword (for example,
specifying a method's return type `this` is not allowed). Use explicit type
instead.
**TypeScript** **TypeScript**
...@@ -959,7 +961,9 @@ type N = number ...@@ -959,7 +961,9 @@ type N = number
**Severity: error** **Severity: error**
ArkTS does not support indexed access for class fields. Use dot notation ArkTS does not support indexed access for class fields. Use dot notation
instead. instead. An exception are all typed arrays from the standard library
(for example, `Int32Array`), which support access to their elements through
`container[index]` syntax.
**TypeScript** **TypeScript**
...@@ -975,6 +979,9 @@ let x = p["x"] ...@@ -975,6 +979,9 @@ let x = p["x"]
class Point {x: number = 0; y: number = 0} class Point {x: number = 0; y: number = 0}
let p: Point = {x: 1, y: 2} let p: Point = {x: 1, y: 2}
let x = p.x let x = p.x
let arr = new Int32Array(1)
console.log(arr[0])
``` ```
## Recipe: Structural identity is not supported ## Recipe: Structural identity is not supported
...@@ -1541,33 +1548,6 @@ let a2: C[] = [{n: 1, s: "1"}, {n: 2, s : "2"}] // ditto ...@@ -1541,33 +1548,6 @@ let a2: C[] = [{n: 1, s: "1"}, {n: 2, s : "2"}] // ditto
* Recipe: Object literal must correspond to some explicitly declared class or interface * Recipe: Object literal must correspond to some explicitly declared class or interface
* Recipe: Object literals cannot be used as type declarations * Recipe: Object literals cannot be used as type declarations
## Recipe: Lambdas require explicit type annotation for parameters
**Rule `arkts-explicit-param-types-in-lambdas`**
**Severity: error**
Currently, ArkTS requires the types of lambda parameters
to be explicitly specified.
**TypeScript**
```typescript
// Compile-time error only with noImplicitAny:
let f = (s /* type any is assumed */) => {
console.log(s)
}
```
**ArkTS**
```typescript
// Explicit types for lambda parameters are mandatory:
let f = (s: string) => {
console.log(s)
}
```
## Recipe: Use arrow functions instead of function expressions ## Recipe: Use arrow functions instead of function expressions
**Rule `arkts-no-func-expressions`** **Rule `arkts-no-func-expressions`**
...@@ -1989,9 +1969,9 @@ let f = "string" + true // "stringtrue" ...@@ -1989,9 +1969,9 @@ let f = "string" + true // "stringtrue"
let g = (new Object()) + "string" // "[object Object]string" let g = (new Object()) + "string" // "[object Object]string"
let i = true + true // JS: 2, TS: compile-time error let i = true + true // compile-time error
let j = true + 2 // JS: 3, TS: compile-time error let j = true + 2 // compile-time error
let k = E.E1 + true // JS: 1, TS: compile-time error let k = E.E1 + true // compile-time error
``` ```
**ArkTS** **ArkTS**
...@@ -2011,7 +1991,7 @@ let g = (new Object()).toString() + "string" ...@@ -2011,7 +1991,7 @@ let g = (new Object()).toString() + "string"
let i = true + true // compile-time error let i = true + true // compile-time error
let j = true + 2 // compile-time error let j = true + 2 // compile-time error
let k = E.E1 + true // compile-time error let k = E.E1 + true // compile-time error
``` ```
...@@ -2341,7 +2321,8 @@ iterate over data. ...@@ -2341,7 +2321,8 @@ iterate over data.
**Severity: error** **Severity: error**
ArkTS supports the iteration over arrays and strings by the `for .. of` loop, ArkTS supports the iteration over arrays and strings by the `for .. of` loop,
but does not support the iteration of objects content. but does not support the iteration of objects content. All typed arrays from
the standard library (for example, `Int32Array`) are also supported.
**TypeScript** **TypeScript**
...@@ -2433,7 +2414,8 @@ console.log("Area: ", Math.PI * r * r) ...@@ -2433,7 +2414,8 @@ console.log("Area: ", Math.PI * r * r)
**Severity: error** **Severity: error**
ArkTS supports `case` statements that contain only compile-time values. ArkTS supports `case` statements that contain only compile-time values,
top-level scope `const` values, and `static readonly` class fields.
Use `if` statements as an alternative. Use `if` statements as an alternative.
**TypeScript** **TypeScript**
...@@ -2907,7 +2889,8 @@ function main(): void { ...@@ -2907,7 +2889,8 @@ function main(): void {
The only supported scenario for the spread operator is to spread an array into The only supported scenario for the spread operator is to spread an array into
the rest parameter. Otherwise, manually “unpack” data from arrays and objects, the rest parameter. Otherwise, manually “unpack” data from arrays and objects,
where necessary. where necessary. All typed arrays from the standard library (for example,
`Int32Array`) are also supported.
**TypeScript** **TypeScript**
...@@ -3880,34 +3863,6 @@ let ce = new CustomError() ...@@ -3880,34 +3863,6 @@ let ce = new CustomError()
* Recipe: Prototype assignment is not supported * Recipe: Prototype assignment is not supported
## Recipe: Runtime import expressions are not supported
**Rule `arkts-no-runtime-import`**
**Severity: error**
ArkTS does not support such “runtime” import expressions as `await import...`
because in the language import is a compile-time, not a runtime feature.
Use regular import syntax instead.
**TypeScript**
```typescript
const zipUtil = await import("utils/create-zip-file")
```
**ArkTS**
```typescript
import { zipUtil } from "utils/create-zip-file"
```
**See also**
* Recipe: Wildcards in module names are not supported
* Recipe: Universal module definitions (UMD) are not supported
* Recipe: Import assertions are not supported
## Recipe: Definite assignment assertions are not supported ## Recipe: Definite assignment assertions are not supported
**Rule `arkts-no-definite-assignment`** **Rule `arkts-no-definite-assignment`**
...@@ -4065,8 +4020,7 @@ M.abc = 200 ...@@ -4065,8 +4020,7 @@ M.abc = 200
**Severity: error** **Severity: error**
Currently ArkTS does not support utility types from TypeScript extensions to the Currently ArkTS does not support utility types from TypeScript extensions to the
standard library (`Omit`, `Pick`, etc.). Exceptions are: `Partial`, standard library, except following: `Partial`, `Record`.
`Record`.
For the type *Record<K, V>*, the type of an indexing expression *rec[index]* is For the type *Record<K, V>*, the type of an indexing expression *rec[index]* is
of the type *V | undefined*. of the type *V | undefined*.
...@@ -4349,7 +4303,6 @@ import { something } from "module" ...@@ -4349,7 +4303,6 @@ import { something } from "module"
* Recipe: Wildcards in module names are not supported * Recipe: Wildcards in module names are not supported
* Recipe: Universal module definitions (UMD) are not supported * Recipe: Universal module definitions (UMD) are not supported
* Recipe: Runtime import expressions are not supported
## Recipe: Usage of standard library is restricted ## Recipe: Usage of standard library is restricted
...@@ -4364,9 +4317,7 @@ the following APIs is prohibited: ...@@ -4364,9 +4317,7 @@ the following APIs is prohibited:
Properties and functions of the global object: `eval`, Properties and functions of the global object: `eval`,
`Infinity`, `NaN`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`, `Infinity`, `NaN`, `isFinite`, `isNaN`, `parseFloat`, `parseInt`,
`encodeURI`, `encodeURIComponent`, `Encode`, `Encode`, `Decode`, `ParseHexOctet`
`decodeURI`, `decodeURIComponent`, `Decode`,
`escape`, `unescape`, `ParseHexOctet`
`Object`: `__proto__`, `__defineGetter__`, `__defineSetter__`, `Object`: `__proto__`, `__defineGetter__`, `__defineSetter__`,
`__lookupGetter__`, `__lookupSetter__`, `assign`, `create`, `__lookupGetter__`, `__lookupSetter__`, `assign`, `create`,
...@@ -4561,3 +4512,54 @@ class BugReport { ...@@ -4561,3 +4512,54 @@ class BugReport {
} }
``` ```
## Recipe: Classes cannot be used as objects
**Rule `arkts-no-classes-as-obj`**
**Severity: error**
ArkTS does not support using classes as objects (assigning them to variables,
etc.) because in ArkTS, a `class` declaration introduces a new type,
not a value.
**TypeScript**
```typescript
class C {
s: string = ""
n: number = 0
}
let c = C
```
## Recipe: `import` statements after other statements are not allowed
**Rule `arkts-no-misplaced-imports`**
**Severity: error**
In ArkTS, all `import` statements should go before all other statements
in the program.
**TypeScript**
```typescript
class C {
s: string = ""
n: number = 0
}
import foo from "module1"
```
**ArkTS**
```typescript
import foo from "module1"
class C {
s: string = ""
n: number = 0
}
```
...@@ -66,11 +66,14 @@ import fs from '@ohos.file.fs'; ...@@ -66,11 +66,14 @@ import fs from '@ohos.file.fs';
try { try {
let fd = fs.openSync('/path/to/form.png'); let fd = fs.openSync('/path/to/form.png');
let obj = {
'temperature': '21°', let createFormBindingDataParam = new Map<Object, string | object>();
'formImages': { 'image': fd } let formImagesParam = new Map<Object, object>();
}; formImagesParam.set('image', fd);
formBindingData.createFormBindingData(obj); createFormBindingDataParam.set("name", '21°');
createFormBindingDataParam.set('formImages', formImagesParam);
formBindingData.createFormBindingData(createFormBindingDataParam);
} catch (error) { } catch (error) {
console.error(`catch error, code: ${error.code}, message: ${error.message}`); console.error(`catch error, code: ${error.code}, message: ${error.message}`);
} }
......
...@@ -50,18 +50,24 @@ Displays a notification. ...@@ -50,18 +50,24 @@ Displays a notification.
| options | ShowNotificationOptions | No| Notification title.| | options | ShowNotificationOptions | No| Notification title.|
**Example** **Example**
```javascript ```ts
export default { class NotificationClass {
show() { show: Function
notification.show({ }
contentTitle: 'title info',
contentText: 'text', let notificationObj: NotificationClass = {
clickAction: { show() {
bundleName: 'com.example.testapp', notification.show({
abilityName: 'notificationDemo', contentTitle: 'title info',
uri: '/path/to/notification' contentText: 'text',
} clickAction: {
}); bundleName: 'com.example.testapp',
} abilityName: 'notificationDemo',
uri: '/path/to/notification'
}
});
}
} }
export default notificationObj
``` ```
...@@ -46,21 +46,18 @@ ...@@ -46,21 +46,18 @@
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
export default class EntryFormAbility extends FormExtensionAbility { export default class EntryFormAbility extends FormExtensionAbility {
onFormEvent(formId, message) { onFormEvent(formId: string, message: string) {
// Called when a specified message event defined by the form provider is triggered. // Called when a specified message event defined by the form provider is triggered.
console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`); console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);
let formData = { let formData = new Map<Object, string>();
'title': 'Title Update.', // 和卡片布局中对应 formData.set('title', 'Title Update.'); // 和卡片布局中对应
'detail': 'Description update success.', // 和卡片布局中对应 formData.set('detail', 'Description update success.'); // 和卡片布局中对应
};
let formInfo = formBindingData.createFormBindingData(formData) let formInfo = formBindingData.createFormBindingData(formData)
formProvider.updateForm(formId, formInfo).then((data) => { formProvider.updateForm(formId, formInfo).then((data) => {
console.info('FormAbility updateForm success.' + JSON.stringify(data)); console.info('FormAbility updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
}) })
} }
... ...
} }
``` ```
......
...@@ -149,7 +149,7 @@ ...@@ -149,7 +149,7 @@
以导航场景为例,实例化方式如下: 以导航场景为例,实例化方式如下:
```ts ```ts
let requestInfo = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; let requestInfo:geoLocationManager.LocationRequest = {'scenario': geoLocationManager.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
**方式二:** **方式二:**
...@@ -179,14 +179,14 @@ ...@@ -179,14 +179,14 @@
以定位精度优先策略为例,实例化方式如下: 以定位精度优先策略为例,实例化方式如下:
```ts ```ts
let requestInfo = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; let requestInfo:geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
4. 实例化Callback对象,用于向系统提供位置上报的途径。 4. 实例化Callback对象,用于向系统提供位置上报的途径。
应用需要自行实现系统定义好的回调接口,并将其实例化。系统在定位成功确定设备的实时位置结果时,会通过该接口上报给应用。应用程序可以在接口的实现中完成自己的业务逻辑。 应用需要自行实现系统定义好的回调接口,并将其实例化。系统在定位成功确定设备的实时位置结果时,会通过该接口上报给应用。应用程序可以在接口的实现中完成自己的业务逻辑。
```ts ```ts
let locationChange = (location) => { let locationChange = (location:geoLocationManager.Location):void => {
console.log('locationChanger: data: ' + JSON.stringify(location)); console.log('locationChanger: data: ' + JSON.stringify(location));
}; };
``` ```
...@@ -209,10 +209,11 @@ ...@@ -209,10 +209,11 @@
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try { try {
let location = geoLocationManager.getLastLocation(); let location = geoLocationManager.getLastLocation();
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} }
``` ```
...@@ -259,10 +260,11 @@ ...@@ -259,10 +260,11 @@
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try { try {
let isAvailable = geoLocationManager.isGeocoderAvailable(); let isAvailable = geoLocationManager.isGeocoderAvailable();
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} }
``` ```
...@@ -270,7 +272,7 @@ ...@@ -270,7 +272,7 @@
- 调用getAddressesFromLocation,坐标转化地理位置信息。 - 调用getAddressesFromLocation,坐标转化地理位置信息。
```ts ```ts
let reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
try { try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
if (err) { if (err) {
...@@ -280,7 +282,7 @@ ...@@ -280,7 +282,7 @@
} }
}); });
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} }
``` ```
...@@ -288,7 +290,7 @@ ...@@ -288,7 +290,7 @@
- 调用getAddressesFromLocationName位置描述转化坐标。 - 调用getAddressesFromLocationName位置描述转化坐标。
```ts ```ts
let geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1};
try { try {
geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
if (err) { if (err) {
...@@ -298,7 +300,7 @@ ...@@ -298,7 +300,7 @@
} }
}); });
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} }
``` ```
...@@ -332,11 +334,12 @@ ...@@ -332,11 +334,12 @@
1. 使用地理围栏功能,需要有权限ohos.permission.APPROXIMATELY_LOCATION,位置权限申请的方法和步骤见[申请位置权限开发指导](#申请位置权限开发指导) 1. 使用地理围栏功能,需要有权限ohos.permission.APPROXIMATELY_LOCATION,位置权限申请的方法和步骤见[申请位置权限开发指导](#申请位置权限开发指导)
2. 导入[geoLocationManager](../reference/apis/js-apis-geoLocationManager.md)模块[wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)模块。 2. 导入[geoLocationManager](../reference/apis/js-apis-geoLocationManager.md)模块[wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)模块和[BusinessError](../reference/apis/js-apis-base.md)模块。
```ts ```ts
import geoLocationManager from '@ohos.geoLocationManager'; import geoLocationManager from '@ohos.geoLocationManager';
import wantAgent from '@ohos.app.ability.wantAgent'; import wantAgent from '@ohos.app.ability.wantAgent';
import BusinessError from "@ohos.base";
``` ```
3. 创建[WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md)信息。 3. 创建[WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md)信息。
...@@ -344,10 +347,10 @@ ...@@ -344,10 +347,10 @@
场景一:创建拉起Ability的WantAgentInfo信息。 场景一:创建拉起Ability的WantAgentInfo信息。
```ts ```ts
let wantAgentObj = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。 let wantAgentObj:wantAgent.WantAgentInfo|null = null; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。
// 通过WantAgentInfo的operationType设置动作类型 // 通过WantAgentInfo的operationType设置动作类型
let wantAgentInfo = { let wantAgentInfo:wantAgent.WantAgentInfo = {
wants: [ wants: [
{ {
deviceId: '', deviceId: '',
...@@ -368,10 +371,10 @@ ...@@ -368,10 +371,10 @@
场景二:创建发布[公共事件](../application-models/common-event-overview.md)的WantAgentInfo信息。 场景二:创建发布[公共事件](../application-models/common-event-overview.md)的WantAgentInfo信息。
```ts ```ts
let wantAgentObj = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。 let wantAgentObj:wantAgent.WantAgentInfo|null = null; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。
// 通过WantAgentInfo的operationType设置动作类型 // 通过WantAgentInfo的operationType设置动作类型
let wantAgentInfo = { let wantAgentInfo:wantAgent.WantAgentInfo = {
wants: [ wants: [
{ {
action: 'event_name', // 设置事件名 action: 'event_name', // 设置事件名
...@@ -397,11 +400,11 @@ ...@@ -397,11 +400,11 @@
} }
console.info('getWantAgent success'); console.info('getWantAgent success');
wantAgentObj = data; wantAgentObj = data;
let requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
try { try {
geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
} catch (err) { } catch (err) {
console.error("errCode:" + err.code + ",errMessage:" + err.message); console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
} }
}); });
``` ```
......
...@@ -25,13 +25,14 @@ ...@@ -25,13 +25,14 @@
1. 导入模块。 1. 导入模块。
```ts ```ts
import sensor from "@ohos.sensor"; import sensor from '@ohos.sensor';
import { BusinessError } from '@ohos.base';
``` ```
2. 查询设备支持的所有传感器的参数。 2. 查询设备支持的所有传感器的参数。
```ts ```ts
sensor.getSensorList(function (error, data) { sensor.getSensorList((error: BusinessError, data: Array<sensor.Sensor>) => {
if (error) { if (error) {
console.info('getSensorList failed'); console.info('getSensorList failed');
} else { } else {
...@@ -54,19 +55,19 @@ ...@@ -54,19 +55,19 @@
- 通过on()接口,实现对传感器的持续监听,传感器上报周期interval设置为100000000纳秒。 - 通过on()接口,实现对传感器的持续监听,传感器上报周期interval设置为100000000纳秒。
```ts ```ts
sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
}, {'interval': 100000000}); }, { interval: 100000000 });
``` ```
![输入图片说明](figures/002.png) ![输入图片说明](figures/002.png)
- 通过once()接口,实现对传感器的一次监听。 - 通过once()接口,实现对传感器的一次监听。
```ts ```ts
sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { sensor.once(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z); console.info("Succeeded in obtaining data. x: " + data.x + " y: " + data.y + " z: " + data.z);
}); });
``` ```
![输入图片说明](figures/003.png) ![输入图片说明](figures/003.png)
......
...@@ -112,15 +112,17 @@ Json文件共包含2个属性。 ...@@ -112,15 +112,17 @@ Json文件共包含2个属性。
```ts ```ts
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
import { BusinessError } from '@ohos.base';
try { try {
vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 // 使用startVibration需要添加ohos.permission.VIBRATE权限
vibrator.startVibration({
type: 'time', type: 'time',
duration: 1000, duration: 1000,
}, { }, {
id: 0, id: 0,
usage: 'alarm' usage: 'alarm'
}, (error) => { }, (error: BusinessError) => {
if (error) { if (error) {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
return; return;
...@@ -128,7 +130,8 @@ try { ...@@ -128,7 +130,8 @@ try {
console.info('Succeed in starting vibration.'); console.info('Succeed in starting vibration.');
}); });
} catch (err) { } catch (err) {
console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); let e: BusinessError = err as BusinessError;
console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
} }
``` ```
...@@ -136,10 +139,11 @@ try { ...@@ -136,10 +139,11 @@ try {
```ts ```ts
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
import { BusinessError } from '@ohos.base';
try { try {
// 按照VIBRATOR_STOP_MODE_TIME模式停止振动, 使用stopVibration需要添加ohos.permission.VIBRATE权限 // 按照VIBRATOR_STOP_MODE_TIME模式停止振动, 使用stopVibration需要添加ohos.permission.VIBRATE权限
vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, (error: BusinessError) => {
if (error) { if (error) {
console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
return; return;
...@@ -147,7 +151,8 @@ try { ...@@ -147,7 +151,8 @@ try {
console.info('Succeeded in stopping vibration.'); console.info('Succeeded in stopping vibration.');
}) })
} catch (err) { } catch (err) {
console.error(`An unexpected error occurred. Code: ${err.code}, message: ${err.message}`); let e: BusinessError = err as BusinessError;
console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
} }
``` ```
...@@ -155,7 +160,8 @@ try { ...@@ -155,7 +160,8 @@ try {
```ts ```ts
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
// 使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限 import { BusinessError } from '@ohos.base';
try { try {
vibrator.startVibration({ vibrator.startVibration({
type: 'time', type: 'time',
...@@ -163,7 +169,7 @@ try { ...@@ -163,7 +169,7 @@ try {
}, { }, {
id: 0, id: 0,
usage: 'alarm' usage: 'alarm'
}, (error) => { }, (error: BusinessError) => {
if (error) { if (error) {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
return; return;
...@@ -171,7 +177,7 @@ try { ...@@ -171,7 +177,7 @@ try {
console.info('Succeed in starting vibration'); console.info('Succeed in starting vibration');
}); });
// 停止所有类型的马达振动 // 停止所有类型的马达振动
vibrator.stopVibration(function (error) { vibrator.stopVibration((error: BusinessError) => {
if (error) { if (error) {
console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
return; return;
...@@ -179,7 +185,8 @@ try { ...@@ -179,7 +185,8 @@ try {
console.info('Succeed in stopping vibration'); console.info('Succeed in stopping vibration');
}) })
} catch (error) { } catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); let e: BusinessError = error as BusinessError;
console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
} }
``` ```
...@@ -187,10 +194,11 @@ try { ...@@ -187,10 +194,11 @@ try {
```ts ```ts
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
import { BusinessError } from '@ohos.base';
try { try {
// 查询是否支持'haptic.clock.timer' // 查询是否支持'haptic.clock.timer'
vibrator.isSupportEffect('haptic.clock.timer', function (err, state) { vibrator.isSupportEffect('haptic.clock.timer', (err: BusinessError, state: boolean) => {
if (err) { if (err) {
console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to query effect. Code: ${err.code}, message: ${err.message}`);
return; return;
...@@ -198,13 +206,14 @@ try { ...@@ -198,13 +206,14 @@ try {
console.info('Succeed in querying effect'); console.info('Succeed in querying effect');
if (state) { if (state) {
try { try {
vibrator.startVibration({ // 使用startVibration需要添加ohos.permission.VIBRATE权限 // 使用startVibration需要添加ohos.permission.VIBRATE权限
vibrator.startVibration({
type: 'preset', type: 'preset',
effectId: 'haptic.clock.timer', effectId: 'haptic.clock.timer',
count: 1, count: 1,
}, { }, {
usage: 'unknown' usage: 'unknown'
}, (error) => { }, (error: BusinessError) => {
if (error) { if (error) {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
} else { } else {
...@@ -212,12 +221,14 @@ try { ...@@ -212,12 +221,14 @@ try {
} }
}); });
} catch (error) { } catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); let e: BusinessError = error as BusinessError;
console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
} }
} }
}) })
} catch (error) { } catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); let e: BusinessError = error as BusinessError;
console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
} }
``` ```
...@@ -225,20 +236,22 @@ try { ...@@ -225,20 +236,22 @@ try {
```ts ```ts
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
import { BusinessError } from '@ohos.base';
import resourceManager from '@ohos.resourceManager';
// 获取振动文件资源描述符 // 获取振动文件资源描述符
async function getRawfileFd(fileName) { async function getRawfileFd(fileName: string): Promise<resourceManager.RawFileDescriptor> {
let rawFd = await globalThis.getContext().resourceManager.getRawFd(fileName); let rawFd = await getContext().resourceManager.getRawFd(fileName);
return rawFd; return rawFd;
} }
// 关闭振动文件资源描述符 // 关闭振动文件资源描述符
async function closeRawfileFd(fileName) { async function closeRawfileFd(fileName: string): Promise<void> {
await globalThis.getContext().resourceManager.closeRawFd(fileName) await getContext().resourceManager.closeRawFd(fileName)
} }
// 播放自定义振动,使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限 // 播放自定义振动,使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限
async function playCustomHaptic(fileName) { async function playCustomHaptic(fileName: string): Promise<void> {
try { try {
let rawFd = await getRawfileFd(fileName); let rawFd = await getRawfileFd(fileName);
vibrator.startVibration({ vibrator.startVibration({
...@@ -248,10 +261,10 @@ async function playCustomHaptic(fileName) { ...@@ -248,10 +261,10 @@ async function playCustomHaptic(fileName) {
usage: "alarm" usage: "alarm"
}).then(() => { }).then(() => {
console.info('Succeed in starting vibration'); console.info('Succeed in starting vibration');
}, (error) => { }, (error: BusinessError) => {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
}); });
vibrator.stopVibration(function (error) { vibrator.stopVibration((error: BusinessError) => {
if (error) { if (error) {
console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
return; return;
...@@ -260,7 +273,8 @@ async function playCustomHaptic(fileName) { ...@@ -260,7 +273,8 @@ async function playCustomHaptic(fileName) {
}) })
await closeRawfileFd(fileName); await closeRawfileFd(fileName);
} catch (error) { } catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); let e: BusinessError = error as BusinessError;
console.error(`An unexpected error occurred. Code: ${e.code}, message: ${e.message}`);
} }
} }
``` ```
......
...@@ -13,10 +13,10 @@ ...@@ -13,10 +13,10 @@
``` ```
2. 通过getCameraManager()方法,获取cameraManager对象。 2. 通过getCameraManager()方法,获取cameraManager对象。
[各类Context的获取方式](../application-models/application-context-stage.md)
```ts ```ts
let cameraManager: camera.CameraManager; let cameraManager: camera.CameraManager;
let context: Context = getContext(this); // [各类Context的获取方式](../application-models/application-context-stage.md) let context: Context = getContext(this);
cameraManager = camera.getCameraManager(context); cameraManager = camera.getCameraManager(context);
``` ```
...@@ -29,15 +29,15 @@ ...@@ -29,15 +29,15 @@
```ts ```ts
let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras(); let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
if (cameraArray != undefined && cameraArray.length <= 0) { if (cameraArray != undefined && cameraArray.length <= 0) {
console.error("cameraManager.getSupportedCameras error"); console.error("cameraManager.getSupportedCameras error");
return; return;
} }
for (let index = 0; index < cameraArray.length; index++) { for (let index = 0; index < cameraArray.length; index++) {
console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID
console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置 console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置
console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型 console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型
console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型 console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型
} }
``` ```
...@@ -47,22 +47,23 @@ ...@@ -47,22 +47,23 @@
// 创建相机输入流 // 创建相机输入流
let cameraInput: camera.CameraInput; let cameraInput: camera.CameraInput;
try { try {
cameraInput = cameraManager.createCameraInput(cameraArray[0]); cameraInput = cameraManager.createCameraInput(cameraArray[0]);
} catch (error) { } catch (error) {
console.error('Failed to createCameraInput errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to createCameraInput errorCode = ' + err.code);
} }
// 监听cameraInput错误信息 // 监听cameraInput错误信息
let cameraDevice: camera.CameraDevice = cameraArray[0]; let cameraDevice: camera.CameraDevice = cameraArray[0];
cameraInput.on('error', cameraDevice, (error: BusinessError) => { cameraInput.on('error', cameraDevice, (error: BusinessError) => {
console.info(`Camera input error code: ${error.code}`); console.info(`Camera input error code: ${error.code}`);
}); });
// 打开相机 // 打开相机
await cameraInput.open(); await cameraInput.open();
// 获取相机设备支持的输出流能力 // 获取相机设备支持的输出流能力
let cameraOutputCapability: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]); let cameraOutputCapability: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]);
if (!cameraOutputCapability) { if (!cameraOutputCapability) {
console.error("cameraManager.getSupportedOutputCapability error"); console.error("cameraManager.getSupportedOutputCapability error");
return; return;
} }
console.info("outputCapability: " + JSON.stringify(cameraOutputCapability)); console.info("outputCapability: " + JSON.stringify(cameraOutputCapability));
``` ```
......
...@@ -16,8 +16,8 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 ...@@ -16,8 +16,8 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递
try { try {
metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes); metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes);
} catch (error) { } catch (error) {
// 失败返回错误码error.code并处理 let err = error as BusinessError;
console.info(error.code); console.info('Failed to createMetadataOutput, error code: '+ err.code);
} }
``` ```
...@@ -26,8 +26,8 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 ...@@ -26,8 +26,8 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递
```ts ```ts
metadataOutput.start().then(() => { metadataOutput.start().then(() => {
console.info('Callback returned with metadataOutput started.'); console.info('Callback returned with metadataOutput started.');
}).catch((err) => { }).catch((err: BusinessError) => {
console.info('Failed to metadataOutput start '+ err.code); console.info('Failed to metadataOutput start, error code: '+ err.code);
}); });
``` ```
...@@ -36,7 +36,7 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递 ...@@ -36,7 +36,7 @@ Metadata主要是通过一个TAG(Key),去找对应的Data,用于传递
```ts ```ts
metadataOutput.stop().then(() => { metadataOutput.stop().then(() => {
console.info('Callback returned with metadataOutput stopped.'); console.info('Callback returned with metadataOutput stopped.');
}).catch((err) => { }).catch((err: BusinessError) => {
console.info('Failed to metadataOutput stop '+ err.code); console.info('Failed to metadataOutput stop '+ err.code);
}); });
``` ```
......
# 人像模式拍照 # 人像模式拍照实现方案
## 开发流程 ## 开发流程
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
![portraitgraphing Development Process](figures/portrait-capture-development-process.png) ![portraitgraphing Development Process](figures/portrait-capture-development-process.png)
## 完整示例 ## 完整示例
[各类Context的获取方式](../application-models/application-context-stage.md)
```ts ```ts
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
...@@ -17,17 +17,17 @@ import media from '@ohos.multimedia.media'; ...@@ -17,17 +17,17 @@ import media from '@ohos.multimedia.media';
// 创建CameraManager对象 // 创建CameraManager对象
let context: Context = getContext(this); // [各类Context的获取方式](../application-models/application-context-stage.md) let context: Context = getContext(this);
let cameraManager: camera.CameraManager = camera.getCameraManager(context); let cameraManager: camera.CameraManager = camera.getCameraManager(context);
if (!cameraManager) { if (!cameraManager) {
console.error("camera.getCameraManager error"); console.error("camera.getCameraManager error");
return; return;
} }
// 创建ModeManager对象 // 创建ModeManager对象
let modeManager: camera.ModeManager = camera.getModeManager(context); let modeManager: camera.ModeManager = camera.getModeManager(context);
if (!cameraManager) { if (!cameraManager) {
console.error("camera.getModeManager error"); console.error("camera.getModeManager error");
return; return;
} }
// 监听相机状态变化 // 监听相机状态变化
cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => { cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
...@@ -37,34 +37,35 @@ cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.C ...@@ -37,34 +37,35 @@ cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.C
// 获取相机列表 // 获取相机列表
let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras(); let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
if (cameraArray.length <= 0) { if (cameraArray.length <= 0) {
console.error("cameraManager.getSupportedCameras error"); console.error("cameraManager.getSupportedCameras error");
return; return;
} }
for (let index = 0; index < cameraArray.length; index++) { for (let index = 0; index < cameraArray.length; index++) {
console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID console.info('cameraId : ' + cameraArray[index].cameraId); // 获取相机ID
console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置 console.info('cameraPosition : ' + cameraArray[index].cameraPosition); // 获取相机位置
console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型 console.info('cameraType : ' + cameraArray[index].cameraType); // 获取相机类型
console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型 console.info('connectionType : ' + cameraArray[index].connectionType); // 获取相机连接类型
} }
// 获取模式列表 // 获取模式列表
let cameraModeArray: Array<camera.CameraMode> = modeManager.getSupportedModes(cameraArray[0]); let cameraModeArray: Array<camera.CameraMode> = modeManager.getSupportedModes(cameraArray[0]);
if (cameraModeArray.length <= 0) { if (cameraModeArray.length <= 0) {
console.error("modeManager.getSupportedModes error"); console.error("modeManager.getSupportedModes error");
return; return;
} }
// 创建相机输入流 // 创建相机输入流
let cameraInput: camera.CameraInput; let cameraInput: camera.CameraInput;
try { try {
cameraInput = cameraManager.createCameraInput(cameraArray[0]); cameraInput = cameraManager.createCameraInput(cameraArray[0]);
} catch (error) { } catch (error) {
console.error('Failed to createCameraInput errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to createCameraInput errorCode = ' + err.code);
} }
// 监听cameraInput错误信息 // 监听cameraInput错误信息
let cameraDevice: camera.CameraDevice = cameraArray[0]; let cameraDevice: camera.CameraDevice = cameraArray[0];
cameraInput.on('error', cameraDevice, (error: BusinessError) => { cameraInput.on('error', cameraDevice, (error: BusinessError) => {
console.info(`Camera input error code: ${error.code}`); console.info(`Camera input error code: ${error.code}`);
}) })
// 打开相机 // 打开相机
...@@ -73,82 +74,89 @@ await cameraInput.open(); ...@@ -73,82 +74,89 @@ await cameraInput.open();
// 获取当前模式相机设备支持的输出流能力 // 获取当前模式相机设备支持的输出流能力
let cameraOutputCap: camera.CameraOutputCapability = modeManager.getSupportedOutputCapability(cameraArray[0], cameraModeArray[0]); let cameraOutputCap: camera.CameraOutputCapability = modeManager.getSupportedOutputCapability(cameraArray[0], cameraModeArray[0]);
if (!cameraOutputCap) { if (!cameraOutputCap) {
console.error("modeManager.getSupportedOutputCapability error") console.error("modeManager.getSupportedOutputCapability error");
return; return;
} }
console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles; let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
if (!previewProfilesArray) { if (!previewProfilesArray) {
console.error("createOutput previewProfilesArray == null || undefined") console.error("createOutput previewProfilesArray == null || undefined");
} }
let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles; let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
if (!photoProfilesArray) { if (!photoProfilesArray) {
console.error("createOutput photoProfilesArray == null || undefined") console.error("createOutput photoProfilesArray == null || undefined");
} }
// 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface // 创建预览输出流,其中参数 surfaceId 参考上文 XComponent 组件,预览流为XComponent组件提供的surface
let previewOutput: camera.PreviewOutput; let previewOutput: camera.PreviewOutput;
try { try {
previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
} catch (error) { } catch (error) {
console.error("Failed to create the PreviewOutput instance."); let err = error as BusinessError;
console.error("Failed to create the PreviewOutput instance. error code:" + err.code);
} }
// 监听预览输出错误信息 // 监听预览输出错误信息
previewOutput.on('error', (error: BusinessError) => { previewOutput.on('error', (error: BusinessError) => {
console.info(`Preview output error code: ${error.code}`); console.info(`Preview output error code: ${error.code}`);
}) })
// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 // 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置
let imageReceiver: image.ImageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) let imageReceiver: image.ImageReceiver = image.createImageReceiver(1920, 1080, 4, 8);
// 获取照片显示SurfaceId // 获取照片显示SurfaceId
let photoSurfaceId: string = await imageReceiver.getReceivingSurfaceId() let photoSurfaceId: string = await imageReceiver.getReceivingSurfaceId();
// 创建拍照输出流 // 创建拍照输出流
let photoOutput: camera.PhotoOutput; let photoOutput: camera.PhotoOutput;
try { try {
photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId);
} catch (error) { } catch (error) {
console.error('Failed to createPhotoOutput errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to createPhotoOutput errorCode = ' + err.code);
} }
//创建portrait会话 //创建portrait会话
let portraitSession: camera.CaptureSession; let portraitSession: camera.CaptureSession;
try { try {
portraitSession = modeManager.createCaptureSession(cameraModeArray[0]); portraitSession = modeManager.createCaptureSession(cameraModeArray[0]);
} catch (error) { } catch (error) {
console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to create the CaptureSession instance. errorCode = ' + err.code);
} }
// 监听portraitSession错误信息 // 监听portraitSession错误信息
portraitSession.on('error', (error: BusinessError) => { portraitSession.on('error', (error: BusinessError) => {
console.info(`Capture session error code: ${error.code}`); console.info(`Capture session error code: ${error.code}`);
}); });
// 开始配置会话 // 开始配置会话
try { try {
portraitSession.beginConfig(); portraitSession.beginConfig();
} catch (error) { } catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to beginConfig. errorCode = ' + err.code);
} }
// 向会话中添加相机输入流 // 向会话中添加相机输入流
try { try {
portraitSession.addInput(cameraInput); portraitSession.addInput(cameraInput);
} catch (error) { } catch (error) {
console.error('Failed to addInput. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addInput. errorCode = ' + err.code);
} }
// 向会话中添加预览输出流 // 向会话中添加预览输出流
try { try {
portraitSession.addOutput(previewOutput); portraitSession.addOutput(previewOutput);
} catch (error) { } catch (error) {
console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code);
} }
// 向会话中添加拍照输出流 // 向会话中添加拍照输出流
try { try {
portraitSession.addOutput(photoOutput); portraitSession.addOutput(photoOutput);
} catch (error) { } catch (error) {
console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
} }
// 提交会话配置 // 提交会话配置
...@@ -156,86 +164,97 @@ await portraitSession.commitConfig(); ...@@ -156,86 +164,97 @@ await portraitSession.commitConfig();
// 启动会话 // 启动会话
await portraitSession.start().then(() => { await portraitSession.start().then(() => {
console.info('Promise returned to indicate the session start success.'); console.info('Promise returned to indicate the session start success.');
}) })
// 获取支持的美颜类型 // 获取支持的美颜类型
let beautyTypes: Array<camera.BeautyType>; let beautyTypes: Array<camera.BeautyType>;
try { try {
beautyTypes = portraitSession.getSupportedBeautyTypes(); beautyTypes = portraitSession.getSupportedBeautyTypes();
} catch (error) { } catch (error) {
console.error('Failed to get the beauty types. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the beauty types. errorCode = ' + err.code);
} }
// 获取支持的美颜类型对应的美颜强度范围 // 获取支持的美颜类型对应的美颜强度范围
let beautyRanges: Array<number>; let beautyRanges: Array<number>;
try { try {
beautyRanges = portraitSession.getSupportedBeautyRanges(beautyTypes[0]); beautyRanges = portraitSession.getSupportedBeautyRanges(beautyTypes[0]);
} catch (error) { } catch (error) {
console.error('Failed to get the beauty types ranges. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the beauty types ranges. errorCode = ' + err.code);
} }
// 设置美颜类型及对应的美颜强度 // 设置美颜类型及对应的美颜强度
try { try {
portraitSession.setBeauty(beautyTypes[0], beautyRanges[0]); portraitSession.setBeauty(beautyTypes[0], beautyRanges[0]);
} catch (error) { } catch (error) {
console.error('Failed to set the beauty type value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the beauty type value. errorCode = ' + err.code);
} }
// 获取已经设置的美颜类型对应的美颜强度 // 获取已经设置的美颜类型对应的美颜强度
let beautyLevel: number; let beautyLevel: number;
try { try {
beautyLevel = portraitSession.getBeauty(beautyTypes[0]); beautyLevel = portraitSession.getBeauty(beautyTypes[0]);
} catch (error) { } catch (error) {
console.error('Failed to get the beauty type value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the beauty type value. errorCode = ' + err.code);
} }
// 获取支持的滤镜类型 // 获取支持的滤镜类型
let filterTypes: Array<camera.FilterType>; let filterTypes: Array<camera.FilterType>;
try { try {
filterTypes = portraitSession.getSupportedFilters(); filterTypes = portraitSession.getSupportedFilters();
} catch (error) { } catch (error) {
console.error('Failed to get the filter types. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the filter types. errorCode = ' + err.code);
} }
// 设置滤镜类型 // 设置滤镜类型
try { try {
portraitSession.setFilter(filterTypes[0]); portraitSession.setFilter(filterTypes[0]);
} catch (error) { } catch (error) {
console.error('Failed to set the filter type value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the filter type value. errorCode = ' + err.code);
} }
// 获取已经设置的滤镜类型 // 获取已经设置的滤镜类型
let filter: number; let filter: number;
try { try {
filter = portraitSession.getFilter(); filter = portraitSession.getFilter();
} catch (error) { } catch (error) {
console.error('Failed to get the filter type value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the filter type value. errorCode = ' + err.code);
} }
// 获取支持的虚化类型 // 获取支持的虚化类型
let portraitTypes: Array<camera.PortraitEffect>; let portraitTypes: Array<camera.PortraitEffect>;
try { try {
portraitTypes = portraitSession.getSupportedPortraitEffects(); portraitTypes = portraitSession.getSupportedPortraitEffects();
} catch (error) { } catch (error) {
console.error('Failed to get the portrait effects types. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the portrait effects types. errorCode = ' + err.code);
} }
// 设置虚化类型 // 设置虚化类型
try { try {
portraitSession.setPortraitEffect(portraitTypes[0]); portraitSession.setPortraitEffect(portraitTypes[0]);
} catch (error) { } catch (error) {
console.error('Failed to set the portrait effects value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the portrait effects value. errorCode = ' + err.code);
} }
// 获取已经设置的虚化类型 // 获取已经设置的虚化类型
let effect: camera.PortraitEffect; let effect: camera.PortraitEffect;
try { try {
effect = portraitSession.getPortraitEffect(); effect = portraitSession.getPortraitEffect();
} catch (error) { } catch (error) {
console.error('Failed to get the portrait effects value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the portrait effects value. errorCode = ' + err.code);
} }
let captureSettings: camera.PhotoCaptureSetting;
// 使用当前拍照设置进行拍照 // 使用当前拍照设置进行拍照
photoOutput.capture(settings, async (err: BusinessError) => { photoOutput.capture(captureSettings, async (err: BusinessError) => {
if (err) { if (err) {
console.error('Failed to capture the photo ${err.message}'); console.error('Failed to capture the photo ${err.message}');
return; return;
} }
console.info('Callback invoked to indicate the photo capture request success.'); console.info('Callback invoked to indicate the photo capture request success.');
}); });
// 停止当前会话 // 停止当前会话
portraitSession.stop(); portraitSession.stop();
......
...@@ -31,19 +31,21 @@ ...@@ -31,19 +31,21 @@
![](figures/deferred-surface-sequence-diagram.png) ![](figures/deferred-surface-sequence-diagram.png)
[各类Context的获取方式](../application-models/application-context-stage.md)
```js ```js
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
function async preview(context: Context, cameraInfo: camera.Device, previewProfile: camera.Profile, photoProfile: camera.Profile, surfaceId: string): Promise<void> { async function Preview(context: Context, cameraInfo: camera.CameraDevice, previewProfile: camera.Profile, photoProfile: camera.Profile, surfaceId: string): Promise<void> {
const cameraManager: camera.CameraManager = camera.getCameraManager(context); const cameraManager: camera.CameraManager = camera.getCameraManager(context);
const cameraInput camera.CameraInput = await cameraManager.createCameraInput(cameraInfo); const cameraInput: camera.CameraInput = cameraManager.createCameraInput(cameraInfo);
const previewOutput: camera.PreviewOutput = await cameraManager.createDeferredPreviewOutput(previewProfile); const previewOutput: camera.PreviewOutput = await cameraManager.createDeferredPreviewOutput(previewProfile);
const photoOutput: camera.PhotoOutput = await cameraManager.createPhotoOutput(photoProfile); const photoOutput: camera.PhotoOutput = cameraManager.createPhotoOutput(photoProfile, surfaceId);
const session: camera.CaptureSession = await mCameraManager.createCaptureSession(); const session: camera.CaptureSession = cameraManager.createCaptureSession();
await session.beginConfig(); session.beginConfig();
await session.addInput(cameraInput); session.addInput(cameraInput);
await session.addOutput(previewOutput); session.addOutput(previewOutput);
await session.addOutput(photoOutput); session.addOutput(photoOutput);
await session.commitConfig(); await session.commitConfig();
await session.start(); await session.start();
await previewOutput.addDeferredSurface(surfaceId); await previewOutput.addDeferredSurface(surfaceId);
...@@ -79,30 +81,31 @@ function async preview(context: Context, cameraInfo: camera.Device, previewProfi ...@@ -79,30 +81,31 @@ function async preview(context: Context, cameraInfo: camera.Device, previewProfi
![](figures/quick-thumbnail-sequence-diagram.png) ![](figures/quick-thumbnail-sequence-diagram.png)
[各类Context的获取方式](../application-models/application-context-stage.md)
```js ```js
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
let context: Context = getContext(this); // [各类Context的获取方式](../application-models/application-context-stage.md) let context: Context = getContext(this);
let cameraManager: camera.CameraManager = camera.getCameraManager(context); let cameraManager: camera.CameraManager = camera.getCameraManager(context);
let cameras: Array<camera.CameraDevice> = cameraManager.getSupportedCameras(); let cameras: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
// 创建CaptureSession实例 // 创建CaptureSession实例
let captureSession: camera.CaptureSession = await cameraManager.createCaptureSession(); let captureSession: camera.CaptureSession = cameraManager.createCaptureSession();
// 开始配置会话 // 开始配置会话
await captureSession.beginConfig(); captureSession.beginConfig();
// 把CameraInput加入到会话 // 把CameraInput加入到会话
let cameraInput: camera.CameraInput = await cameraManager.createCameraInput(cameras[0]); let cameraInput: camera.CameraInput = cameraManager.createCameraInput(cameras[0]);
await cameraInput.open(); cameraInput.open();
await captureSession.addInput(cameraInput); captureSession.addInput(cameraInput);
// 把PhotoOutPut加入到会话 // 把PhotoOutPut加入到会话
let photoOutPut: camera.PhotoOutput = await cameraManager.createPhotoOutput(photoProfile, surfaceId); let photoOutPut: camera.PhotoOutput = cameraManager.createPhotoOutput(photoProfile, surfaceId);
await captureSession.addOutput(photoOutPut); captureSession.addOutput(photoOutPut);
let isSupported: boolean = photoOutPut.isQuickThumbnailSupported(); let isSupported: boolean = photoOutPut.isQuickThumbnailSupported();
if (isSupported) { if (isSupported) {
// 使能快速缩略图 // 使能快速缩略图
photoOutPut.enableQuickThumbnail(true); photoOutPut.enableQuickThumbnail(true);
photoOutPut.on('quickThumbnail', (err: BusinessError, pixelmap: image.PixelMap) => { photoOutPut.on('quickThumbnail', (err: BusinessError, pixelmap: image.PixelMap) => {
if (err || pixelmap === undefined) { if (err || pixelmap === undefined) {
console.error('photoOutPut on thumbnail failed'); console.error('photoOutPut on thumbnail failed');
return; return;
} }
// 显示或保存pixelmap // 显示或保存pixelmap
showOrSavePicture(pixelmap); showOrSavePicture(pixelmap);
...@@ -135,16 +138,19 @@ if (isSupported) { ...@@ -135,16 +138,19 @@ if (isSupported) {
![](figures/prelaunch-sequence-diagram.png) ![](figures/prelaunch-sequence-diagram.png)
[各类Context的获取方式](../application-models/application-context-stage.md)
- **桌面应用** - **桌面应用**
```js ```js
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
let context: Context = getContext(this);
let cameraManager: camera.CameraManager = camera.getCameraManager(globalThis.abilityContext); let cameraManager: camera.CameraManager = camera.getCameraManager(context);
try { try {
cameraManager.prelaunch(); cameraManager.prelaunch();
} catch (error) { } catch (error) {
console.error(`catch error: Code: ${error.code}, message: ${error.message}`); let err = error as BusinessError;
console.error(`catch error: Code: ${err.code}, message: ${err.message}`);
} }
``` ```
...@@ -156,14 +162,15 @@ if (isSupported) { ...@@ -156,14 +162,15 @@ if (isSupported) {
```js ```js
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
let context: Context = getContext(this);
cameraManager: camera.CameraManager = camera.getCameraManager(globalThis.abilityContext); let cameraManager: camera.CameraManager = camera.getCameraManager(context);
let cameras: Array<camera.CameraDevice> = cameraManager.getSupportedCameras(); let cameras: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
if(cameraManager.isPrelaunchSupported(cameras[0])) { if(cameraManager.isPrelaunchSupported(cameras[0])) {
try { try {
cameraManager.setPrelaunchConfig({cameraDevice: cameras[0]}); cameraManager.setPrelaunchConfig({cameraDevice: cameras[0]});
} catch (error) { } catch (error) {
console.error(`catch error: Code: ${error.code}, message: ${error.message}`); let err = error as BusinessError;
console.error(`catch error: Code: ${err.code}, message: ${err.message}`);
} }
} }
``` ```
...@@ -7,11 +7,9 @@ ...@@ -7,11 +7,9 @@
详细的API说明请参考[Camera API参考](../reference/apis/js-apis-camera.md) 详细的API说明请参考[Camera API参考](../reference/apis/js-apis-camera.md)
1. 创建Surface。 1. 创建Surface。
XComponent组件为预览流提供的Surface,而XComponent的能力由UI提供,相关介绍可参考[XComponent组件参考](../reference/arkui-ts/ts-basic-components-xcomponent.md) XComponent组件为预览流提供的Surface,而XComponent的能力由UI提供,相关介绍可参考[XComponent组件参考](../reference/arkui-ts/ts-basic-components-xcomponent.md)
**注**:预览流与录像输出流的分辨率的宽高比要保持一致,如示例代码中宽高比为1920:1080 = 16:9,则需要预览流中的分辨率的宽高比也为16:9,如分辨率选择640:360,或960:540,或1920:1080,以此类推
```ts ```ts
// 创建XComponentController // 创建XComponentController
mXComponentController: XComponentController = new XComponentController; mXComponentController: XComponentController = new XComponentController;
...@@ -26,7 +24,6 @@ ...@@ -26,7 +24,6 @@
}) })
.onLoad(() => { .onLoad(() => {
// 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置
// 预览流与录像输出流的分辨率的宽高比要保持一致
this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}); this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080});
// 获取Surface ID // 获取Surface ID
globalThis.surfaceId = this.mXComponentController.getXComponentSurfaceId(); globalThis.surfaceId = this.mXComponentController.getXComponentSurfaceId();
...@@ -36,22 +33,22 @@ ...@@ -36,22 +33,22 @@
} }
} }
``` ```
2. 通过CameraOutputCapability类中的previewProfiles()方法获取当前设备支持的预览能力,返回previewProfilesArray数组 。通过createPreviewOutput()方法创建预览输出流,其中,createPreviewOutput()方法中的两个参数分别是previewProfilesArray数组中的第一项和步骤一中获取的surfaceId。 2. 通过CameraOutputCapability类中的previewProfiles()方法获取当前设备支持的预览能力,返回previewProfilesArray数组 。通过createPreviewOutput()方法创建预览输出流,其中,createPreviewOutput()方法中的两个参数分别是previewProfilesArray数组中的第一项和步骤一中获取的surfaceId。
```ts ```ts
let previewProfilesArray: Array<camera.Profile> = cameraOutputCapability.previewProfiles; let previewProfilesArray: Array<camera.Profile> = cameraOutputCapability.previewProfiles;
let previewOutput: camera.PreviewOutput; let previewOutput: camera.PreviewOutput;
try { try {
previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
} } catch (error) {
catch (error) { let err = error as BusinessError;
console.error("Failed to create the PreviewOutput instance." + error); console.error("Failed to create the PreviewOutput instance. error code: " + err.code);
} }
``` ```
3. 使能。通过start()方法输出预览流,接口调用失败会返回相应错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode) 3. 使能。通过start()方法输出预览流,接口调用失败会返回相应错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)
```ts ```ts
previewOutput.start().then(() => { previewOutput.start().then(() => {
console.info('Callback returned with previewOutput started.'); console.info('Callback returned with previewOutput started.');
...@@ -66,7 +63,7 @@ ...@@ -66,7 +63,7 @@
在相机应用开发过程中,可以随时监听预览输出流状态,包括预览流启动、预览流结束、预览流输出错误。 在相机应用开发过程中,可以随时监听预览输出流状态,包括预览流启动、预览流结束、预览流输出错误。
- 通过注册固定的frameStart回调函数获取监听预览启动结果,previewOutput创建成功时即可监听,预览第一次曝光时触发,有该事件返回结果则认为预览流已启动。 - 通过注册固定的frameStart回调函数获取监听预览启动结果,previewOutput创建成功时即可监听,预览第一次曝光时触发,有该事件返回结果则认为预览流已启动。
```ts ```ts
previewOutput.on('frameStart', () => { previewOutput.on('frameStart', () => {
console.info('Preview frame started'); console.info('Preview frame started');
...@@ -74,7 +71,7 @@ ...@@ -74,7 +71,7 @@
``` ```
- 通过注册固定的frameEnd回调函数获取监听预览结束结果,previewOutput创建成功时即可监听,预览完成最后一帧时触发,有该事件返回结果则认为预览流已结束。 - 通过注册固定的frameEnd回调函数获取监听预览结束结果,previewOutput创建成功时即可监听,预览完成最后一帧时触发,有该事件返回结果则认为预览流已结束。
```ts ```ts
previewOutput.on('frameEnd', () => { previewOutput.on('frameEnd', () => {
console.info('Preview frame ended'); console.info('Preview frame ended');
...@@ -82,7 +79,7 @@ ...@@ -82,7 +79,7 @@
``` ```
- 通过注册固定的error回调函数获取监听预览输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode) - 通过注册固定的error回调函数获取监听预览输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)
```ts ```ts
previewOutput.on('error', (previewOutputError: BusinessError) => { previewOutput.on('error', (previewOutputError: BusinessError) => {
console.info(`Preview output error code: ${previewOutputError.code}`); console.info(`Preview output error code: ${previewOutputError.code}`);
......
...@@ -8,18 +8,18 @@ ...@@ -8,18 +8,18 @@
## 完整示例 ## 完整示例
[各类Context的获取方式](../application-models/application-context-stage.md)
```ts ```ts
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
// 创建CameraManager对象 // 创建CameraManager对象
let context: Context = getContext(this); // [各类Context的获取方式](../application-models/application-context-stage.md) let context: Context = getContext(this);
let cameraManager: camera.CameraManager = camera.getCameraManager(context); let cameraManager: camera.CameraManager = camera.getCameraManager(context);
if (!cameraManager) { if (!cameraManager) {
console.error("camera.getCameraManager error"); console.error("camera.getCameraManager error");
return; return;
} }
// 监听相机状态变化 // 监听相机状态变化
cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => { cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
...@@ -27,6 +27,12 @@ cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.C ...@@ -27,6 +27,12 @@ cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.C
console.log(`status: ${cameraStatusInfo.status}`); console.log(`status: ${cameraStatusInfo.status}`);
}); });
// 获取相机列表
let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
if (cameraArray.length <= 0) {
console.error("cameraManager.getSupportedCameras error")
return;
}
// 获取相机设备支持的输出流能力 // 获取相机设备支持的输出流能力
let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]); let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0]);
if (!cameraOutputCap) { if (!cameraOutputCap) {
...@@ -38,17 +44,17 @@ console.log("outputCapability: " + JSON.stringify(cameraOutputCap)); ...@@ -38,17 +44,17 @@ console.log("outputCapability: " + JSON.stringify(cameraOutputCap));
let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles; let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
if (!previewProfilesArray) { if (!previewProfilesArray) {
console.error("createOutput previewProfilesArray == null || undefined"); console.error("createOutput previewProfilesArray == null || undefined");
} }
let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles; let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
if (!photoProfilesArray) { if (!photoProfilesArray) {
console.error("createOutput photoProfilesArray == null || undefined"); console.error("createOutput photoProfilesArray == null || undefined");
} }
let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCap.videoProfiles; let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCap.videoProfiles;
if (!videoProfilesArray) { if (!videoProfilesArray) {
console.error("createOutput videoProfilesArray == null || undefined"); console.error("createOutput videoProfilesArray == null || undefined");
} }
let metadataObjectTypesArray: Array<camera.MetadataObjectType> = cameraOutputCap.supportedMetadataObjectTypes; let metadataObjectTypesArray: Array<camera.MetadataObjectType> = cameraOutputCap.supportedMetadataObjectTypes;
if (!metadataObjectTypesArray) { if (!metadataObjectTypesArray) {
...@@ -68,7 +74,7 @@ let AVRecorderProfile = { ...@@ -68,7 +74,7 @@ let AVRecorderProfile = {
videoFrameHeight : 480, videoFrameHeight : 480,
videoFrameRate : 30 videoFrameRate : 30
}; };
let AVRecorderConfig = { let aVRecorderConfig = {
audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
profile : AVRecorderProfile, profile : AVRecorderProfile,
...@@ -87,7 +93,7 @@ media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => { ...@@ -87,7 +93,7 @@ media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => {
} }
}); });
avRecorder.prepare(AVRecorderConfig: media.AVRecorderConfig, (err: BusinessError) => { avRecorder.prepare(aVRecorderConfig, (err: BusinessError) => {
if (err == null) { if (err == null) {
console.log('prepare success'); console.log('prepare success');
} else { } else {
...@@ -138,13 +144,6 @@ try { ...@@ -138,13 +144,6 @@ try {
console.error('Failed to beginConfig. errorCode = ' + error.code); console.error('Failed to beginConfig. errorCode = ' + error.code);
} }
// 获取相机列表
let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
if (cameraArray.length <= 0) {
console.error("cameraManager.getSupportedCameras error")
return;
}
// 创建相机输入流 // 创建相机输入流
let cameraInput: camera.CameraInput; let cameraInput: camera.CameraInput;
try { try {
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
详细的API说明请参考[Camera API参考](../reference/apis/js-apis-camera.md) 详细的API说明请参考[Camera API参考](../reference/apis/js-apis-camera.md)
1. 导入media模块。创建拍照输出流的SurfaceId以及拍照输出的数据,都需要用到系统提供的[media接口](../reference/apis/js-apis-media.md)能力,导入media接口的方法如下。 1. 导入media模块。创建拍照输出流的SurfaceId以及拍照输出的数据,都需要用到系统提供的[media接口](../reference/apis/js-apis-media.md)能力,导入media接口的方法如下。
```ts ```ts
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
``` ```
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
2. 创建Surface。 2. 创建Surface。
系统提供的media接口可以创建一个录像AVRecorder实例,通过该实例的getInputSurface方法获取SurfaceId,与录像输出流做关联,处理录像输出流输出的数据。 系统提供的media接口可以创建一个录像AVRecorder实例,通过该实例的getInputSurface方法获取SurfaceId,与录像输出流做关联,处理录像输出流输出的数据。
```ts ```ts
let avRecorder: media.AVRecorder; let avRecorder: media.AVRecorder;
media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => { media.createAVRecorder((error: BusinessError, recorder: media.AVRecorder) => {
...@@ -26,8 +26,9 @@ ...@@ -26,8 +26,9 @@
console.info(`createAVRecorder fail, error:${error}`); console.info(`createAVRecorder fail, error:${error}`);
} }
}); });
// AVRecorderConfig可参考下一章节 // aVRecorderConfig可参考下一章节
avRecorder.prepare(AVRecorderConfig: media.AVRecorderConfig, (err: BusinessError) => { let aVRecorderConfig: media.AVRecorderConfig;
avRecorder.prepare(aVRecorderConfig, (err: BusinessError) => {
if (err == null) { if (err == null) {
console.log('prepare success'); console.log('prepare success');
} else { } else {
...@@ -35,28 +36,26 @@ ...@@ -35,28 +36,26 @@
} }
}); });
let videoSurfaceId: string = null; let videoSurfaceId: string = null;
avRecorder.getInputSurface().then((surfaceId: string) => { avRecorder.getInputSurface().then((surfaceId: string) => {
console.info('getInputSurface success'); console.info('getInputSurface success');
videoSurfaceId = surfaceId; videoSurfaceId = surfaceId;
}).catch((err) => { }).catch((err: BusinessError) => {
console.info('getInputSurface failed and catch error is ' + err.message); console.info('getInputSurface failed and catch error is ' + err.message);
}); });
``` ```
3. 创建录像输出流。 3. 创建录像输出流。
通过CameraOutputCapability类中的videoProfiles,可获取当前设备支持的录像输出流。然后,定义创建录像的参数,通过createVideoOutput方法创建录像输出流。 通过CameraOutputCapability类中的videoProfiles,可获取当前设备支持的录像输出流。然后,定义创建录像的参数,通过createVideoOutput方法创建录像输出流。
**注**:预览流与录像输出流的分辨率的宽高比要保持一致,如示例代码中宽高比为640:480 = 4:3,则需要预览流中的分辨率的宽高比也为4:3,如分辨率选择640:480,或960:720,或1440:1080,以此类推
```ts ```ts
let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCapability.videoProfiles; let videoProfilesArray: Array<camera.VideoProfile> = cameraOutputCapability.videoProfiles;
if (!videoProfilesArray) { if (!videoProfilesArray) {
console.error("createOutput videoProfilesArray == null || undefined"); console.error("createOutput videoProfilesArray == null || undefined");
} }
// 创建视频录制的参数,预览流与录像输出流的分辨率的宽(videoFrameWidth)高(videoFrameHeight)比要保持一致 // 创建视频录制的参数
let videoConfig = { let videoConfig = {
videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
profile: { profile: {
...@@ -87,10 +86,11 @@ ...@@ -87,10 +86,11 @@
try { try {
videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId); videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId);
} catch (error) { } catch (error) {
console.error('Failed to create the videoOutput instance. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to create the videoOutput instance. errorCode = ' + err.code);
} }
``` ```
4. 开始录像。 4. 开始录像。
先通过videoOutput的start方法启动录像输出流,再通过avRecorder的start方法开始录像。 先通过videoOutput的start方法启动录像输出流,再通过avRecorder的start方法开始录像。
...@@ -110,9 +110,9 @@ ...@@ -110,9 +110,9 @@
``` ```
5. 停止录像。 5. 停止录像。
先通过avRecorder的stop方法停止录像,再通过videoOutput的stop方法停止录像输出流。 先通过avRecorder的stop方法停止录像,再通过videoOutput的stop方法停止录像输出流。
```ts ```ts
videoRecorder.stop().then(() => { videoRecorder.stop().then(() => {
console.info('stop success'); console.info('stop success');
...@@ -133,7 +133,7 @@ ...@@ -133,7 +133,7 @@
在相机应用开发过程中,可以随时监听录像输出流状态,包括录像开始、录像结束、录像流输出的错误。 在相机应用开发过程中,可以随时监听录像输出流状态,包括录像开始、录像结束、录像流输出的错误。
- 通过注册固定的frameStart回调函数获取监听录像开始结果,videoOutput创建成功时即可监听,录像第一次曝光时触发,有该事件返回结果则认为录像开始。 - 通过注册固定的frameStart回调函数获取监听录像开始结果,videoOutput创建成功时即可监听,录像第一次曝光时触发,有该事件返回结果则认为录像开始。
```ts ```ts
videoOutput.on('frameStart', () => { videoOutput.on('frameStart', () => {
console.info('Video frame started'); console.info('Video frame started');
...@@ -141,7 +141,7 @@ ...@@ -141,7 +141,7 @@
``` ```
- 通过注册固定的frameEnd回调函数获取监听录像结束结果,videoOutput创建成功时即可监听,录像完成最后一帧时触发,有该事件返回结果则认为录像流已结束。 - 通过注册固定的frameEnd回调函数获取监听录像结束结果,videoOutput创建成功时即可监听,录像完成最后一帧时触发,有该事件返回结果则认为录像流已结束。
```ts ```ts
videoOutput.on('frameEnd', () => { videoOutput.on('frameEnd', () => {
console.info('Video frame ended'); console.info('Video frame ended');
...@@ -149,7 +149,7 @@ ...@@ -149,7 +149,7 @@
``` ```
- 通过注册固定的error回调函数获取监听录像输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode) - 通过注册固定的error回调函数获取监听录像输出错误结果,callback返回预览输出接口使用错误时对应的错误码,错误码类型参见[CameraErrorCode](../reference/apis/js-apis-camera.md#cameraerrorcode)
```ts ```ts
videoOutput.on('error', (error: BusinessError) => { videoOutput.on('error', (error: BusinessError) => {
console.info(`Video output error code: ${error.code}`); console.info(`Video output error code: ${error.code}`);
......
...@@ -22,7 +22,8 @@ ...@@ -22,7 +22,8 @@
try { try {
captureSession = cameraManager.createCaptureSession(); captureSession = cameraManager.createCaptureSession();
} catch (error) { } catch (error) {
console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to create the CaptureSession instance. errorCode = ' + err.code);
} }
``` ```
...@@ -32,7 +33,8 @@ ...@@ -32,7 +33,8 @@
try { try {
captureSession.beginConfig(); captureSession.beginConfig();
} catch (error) { } catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to beginConfig. errorCode = ' + err.code);
} }
``` ```
...@@ -44,17 +46,20 @@ ...@@ -44,17 +46,20 @@
try { try {
captureSession.addInput(cameraInput); captureSession.addInput(cameraInput);
} catch (error) { } catch (error) {
console.error('Failed to addInput. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addInput. errorCode = ' + err.code);
} }
try { try {
captureSession.addOutput(previewOutput); captureSession.addOutput(previewOutput);
} catch (error) { } catch (error) {
console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code);
} }
try { try {
captureSession.addOutput(photoOutput); captureSession.addOutput(photoOutput);
} catch (error) { } catch (error) {
console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
} }
await captureSession.commitConfig(); await captureSession.commitConfig();
await captureSession.start().then(() => { await captureSession.start().then(() => {
...@@ -69,18 +74,21 @@ ...@@ -69,18 +74,21 @@
try { try {
captureSession.beginConfig(); captureSession.beginConfig();
} catch (error) { } catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to beginConfig. errorCode = ' + err.code);
} }
// 从会话中移除拍照输出流 // 从会话中移除拍照输出流
try { try {
captureSession.removeOutput(photoOutput); captureSession.removeOutput(photoOutput);
} catch (error) { } catch (error) {
console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to removeOutput(photoOutput). errorCode = ' + err.code);
} }
// 向会话中添加视频输出流 // 向会话中添加视频输出流
try { try {
captureSession.addOutput(videoOutput); captureSession.addOutput(videoOutput);
} catch (error) { } catch (error) {
console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addOutput(videoOutput). errorCode = ' + err.code);
} }
``` ```
...@@ -7,14 +7,14 @@ ...@@ -7,14 +7,14 @@
![Photographing Development Process](figures/photographing-development-process.png) ![Photographing Development Process](figures/photographing-development-process.png)
## 完整示例 ## 完整示例
[各类Context的获取方式](../application-models/application-context-stage.md)
```ts ```ts
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
// 创建CameraManager对象 // 创建CameraManager对象
let context: Context = getContext(this); // [各类Context的获取方式](../application-models/application-context-stage.md) let context: Context = getContext(this);
let cameraManager: camera.CameraManager = camera.getCameraManager(context); let cameraManager: camera.CameraManager = camera.getCameraManager(context);
if (!cameraManager) { if (!cameraManager) {
console.error("camera.getCameraManager error"); console.error("camera.getCameraManager error");
...@@ -45,7 +45,8 @@ let cameraInput: camera.CameraInput; ...@@ -45,7 +45,8 @@ let cameraInput: camera.CameraInput;
try { try {
cameraInput = cameraManager.createCameraInput(cameraArray[0]); cameraInput = cameraManager.createCameraInput(cameraArray[0]);
} catch (error) { } catch (error) {
console.error('Failed to createCameraInput errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to createCameraInput errorCode = ' + err.code);
} }
// 监听cameraInput错误信息 // 监听cameraInput错误信息
...@@ -80,7 +81,8 @@ let previewOutput: camera.PreviewOutput; ...@@ -80,7 +81,8 @@ let previewOutput: camera.PreviewOutput;
try { try {
previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
} catch (error) { } catch (error) {
console.error("Failed to create the PreviewOutput instance."); let err = error as BusinessError;
console.error(`Failed to create the PreviewOutput instance. error code: ${err.code}`);
} }
// 监听预览输出错误信息 // 监听预览输出错误信息
...@@ -89,7 +91,7 @@ previewOutput.on('error', (error: BusinessError) => { ...@@ -89,7 +91,7 @@ previewOutput.on('error', (error: BusinessError) => {
}); });
// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 // 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置
let imageReceiver: image.ImageReceiver = await image.createImageReceiver(1920, 1080, 4, 8); let imageReceiver: image.ImageReceiver = image.createImageReceiver(1920, 1080, 4, 8);
// 获取照片显示SurfaceId // 获取照片显示SurfaceId
let photoSurfaceId: string = await imageReceiver.getReceivingSurfaceId(); let photoSurfaceId: string = await imageReceiver.getReceivingSurfaceId();
// 创建拍照输出流 // 创建拍照输出流
...@@ -97,14 +99,16 @@ let photoOutput: camera.PhotoOutput; ...@@ -97,14 +99,16 @@ let photoOutput: camera.PhotoOutput;
try { try {
photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId);
} catch (error) { } catch (error) {
console.error('Failed to createPhotoOutput errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to createPhotoOutput errorCode = ' + err.code);
} }
//创建会话 //创建会话
let captureSession: camera.CaptureSession; let captureSession: camera.CaptureSession;
try { try {
captureSession = cameraManager.createCaptureSession(); captureSession = cameraManager.createCaptureSession();
} catch (error) { } catch (error) {
console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to create the CaptureSession instance. errorCode = ' + err.code);
} }
// 监听session错误信息 // 监听session错误信息
...@@ -116,28 +120,32 @@ captureSession.on('error', (error: BusinessError) => { ...@@ -116,28 +120,32 @@ captureSession.on('error', (error: BusinessError) => {
try { try {
captureSession.beginConfig(); captureSession.beginConfig();
} catch (error) { } catch (error) {
console.error('Failed to beginConfig. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to beginConfig. errorCode = ' + err.code);
} }
// 向会话中添加相机输入流 // 向会话中添加相机输入流
try { try {
captureSession.addInput(cameraInput); captureSession.addInput(cameraInput);
} catch (error) { } catch (error) {
console.error('Failed to addInput. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addInput. errorCode = ' + err.code);
} }
// 向会话中添加预览输出流 // 向会话中添加预览输出流
try { try {
captureSession.addOutput(previewOutput); captureSession.addOutput(previewOutput);
} catch (error) { } catch (error) {
console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code);
} }
// 向会话中添加拍照输出流 // 向会话中添加拍照输出流
try { try {
captureSession.addOutput(photoOutput); captureSession.addOutput(photoOutput);
} catch (error) { } catch (error) {
console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
} }
// 提交会话配置 // 提交会话配置
...@@ -152,7 +160,8 @@ let flashStatus: boolean; ...@@ -152,7 +160,8 @@ let flashStatus: boolean;
try { try {
flashStatus = captureSession.hasFlash(); flashStatus = captureSession.hasFlash();
} catch (error) { } catch (error) {
console.error('Failed to hasFlash. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to hasFlash. errorCode = ' + err.code);
} }
console.info('Promise returned with the flash light support status:' + flashStatus); console.info('Promise returned with the flash light support status:' + flashStatus);
...@@ -163,14 +172,16 @@ if (flashStatus) { ...@@ -163,14 +172,16 @@ if (flashStatus) {
let status: boolean = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); let status: boolean = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
flashModeStatus = status; flashModeStatus = status;
} catch (error) { } catch (error) {
console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code);
} }
if(flashModeStatus) { if(flashModeStatus) {
// 设置自动闪光灯模式 // 设置自动闪光灯模式
try { try {
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
} catch (error) { } catch (error) {
console.error('Failed to set the flash mode. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the flash mode. errorCode = ' + err.code);
} }
} }
} }
...@@ -181,7 +192,8 @@ try { ...@@ -181,7 +192,8 @@ try {
let status: boolean = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); let status: boolean = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
focusModeStatus = status; focusModeStatus = status;
} catch (error) { } catch (error) {
console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code);
} }
if (focusModeStatus) { if (focusModeStatus) {
...@@ -189,23 +201,26 @@ if (focusModeStatus) { ...@@ -189,23 +201,26 @@ if (focusModeStatus) {
try { try {
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
} catch (error) { } catch (error) {
console.error('Failed to set the focus mode. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the focus mode. errorCode = ' + err.code);
} }
} }
// 获取相机支持的可变焦距比范围 // 获取相机支持的可变焦距比范围
let zoomRatioRange; let zoomRatioRange: Array<number>;
try { try {
zoomRatioRange: Array<number> = captureSession.getZoomRatioRange(); zoomRatioRange = captureSession.getZoomRatioRange();
} catch (error) { } catch (error) {
console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the zoom ratio range. errorCode = ' + err.code);
} }
// 设置可变焦距比 // 设置可变焦距比
try { try {
captureSession.setZoomRatio(zoomRatioRange[0]); captureSession.setZoomRatio(zoomRatioRange[0]);
} catch (error) { } catch (error) {
console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the zoom ratio value. errorCode = ' + err.code);
} }
let settings: camera.PhotoCaptureSetting = { let settings: camera.PhotoCaptureSetting = {
quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高 quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高
......
...@@ -17,12 +17,12 @@ ...@@ -17,12 +17,12 @@
通过image的createImageReceiver方法创建ImageReceiver实例,再通过实例的getReceivingSurfaceId方法获取SurfaceId,与拍照输出流相关联,获取拍照输出流的数据。 通过image的createImageReceiver方法创建ImageReceiver实例,再通过实例的getReceivingSurfaceId方法获取SurfaceId,与拍照输出流相关联,获取拍照输出流的数据。
```ts ```ts
function getImageReceiverSurfaceId() { async function getImageReceiverSurfaceId() {
let receiver: image.ImageReceiver = image.createImageReceiver(640, 480, 4, 8); let receiver: image.ImageReceiver = image.createImageReceiver(640, 480, 4, 8);
console.info('before ImageReceiver check'); console.info('before ImageReceiver check');
if (receiver !== undefined) { if (receiver !== undefined) {
console.info('ImageReceiver is ok'); console.info('ImageReceiver is ok');
let photoSurfaceId: string = receiver.getReceivingSurfaceId(); let photoSurfaceId: string = await receiver.getReceivingSurfaceId();
console.info('ImageReceived id: ' + JSON.stringify(photoSurfaceId)); console.info('ImageReceived id: ' + JSON.stringify(photoSurfaceId));
} else { } else {
console.info('ImageReceiver is not ok'); console.info('ImageReceiver is not ok');
...@@ -43,7 +43,8 @@ ...@@ -43,7 +43,8 @@
try { try {
photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId); photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId);
} catch (error) { } catch (error) {
console.error('Failed to createPhotoOutput errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to createPhotoOutput errorCode = ' + err.code);
} }
``` ```
...@@ -57,7 +58,8 @@ ...@@ -57,7 +58,8 @@
try { try {
flashStatus = captureSession.hasFlash(); flashStatus = captureSession.hasFlash();
} catch (error) { } catch (error) {
console.error('Failed to hasFlash. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to hasFlash. errorCode = ' + err.code);
} }
console.info('Promise returned with the flash light support status:' + flashStatus); console.info('Promise returned with the flash light support status:' + flashStatus);
if (flashStatus) { if (flashStatus) {
...@@ -67,14 +69,16 @@ ...@@ -67,14 +69,16 @@
let status: boolean = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); let status: boolean = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
flashModeStatus = status; flashModeStatus = status;
} catch (error) { } catch (error) {
console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code);
} }
if(flashModeStatus) { if(flashModeStatus) {
// 设置自动闪光灯模式 // 设置自动闪光灯模式
try { try {
captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO); captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
} catch (error) { } catch (error) {
console.error('Failed to set the flash mode. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the flash mode. errorCode = ' + err.code);
} }
} }
} }
...@@ -84,14 +88,16 @@ ...@@ -84,14 +88,16 @@
let status: boolean = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); let status: boolean = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
focusModeStatus = status; focusModeStatus = status;
} catch (error) { } catch (error) {
console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code);
} }
if (focusModeStatus) { if (focusModeStatus) {
// 设置连续自动变焦模式 // 设置连续自动变焦模式
try { try {
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO); captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
} catch (error) { } catch (error) {
console.error('Failed to set the focus mode. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the focus mode. errorCode = ' + err.code);
} }
} }
// 获取相机支持的可变焦距比范围 // 获取相机支持的可变焦距比范围
...@@ -99,13 +105,15 @@ ...@@ -99,13 +105,15 @@
try { try {
zoomRatioRange = captureSession.getZoomRatioRange(); zoomRatioRange = captureSession.getZoomRatioRange();
} catch (error) { } catch (error) {
console.error('Failed to get the zoom ratio range. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to get the zoom ratio range. errorCode = ' + err.code);
} }
// 设置可变焦距比 // 设置可变焦距比
try { try {
captureSession.setZoomRatio(zoomRatioRange[0]); captureSession.setZoomRatio(zoomRatioRange[0]);
} catch (error) { } catch (error) {
console.error('Failed to set the zoom ratio value. errorCode = ' + error.code); let err = error as BusinessError;
console.error('Failed to set the zoom ratio value. errorCode = ' + err.code);
} }
``` ```
......
...@@ -35,7 +35,7 @@ OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架 ...@@ -35,7 +35,7 @@ OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架
FA模型和Stage模型的整体架构和设计思想等更多区别,请见[应用模型解读](../application-models/application-model-description.md) FA模型和Stage模型的整体架构和设计思想等更多区别,请见[应用模型解读](../application-models/application-model-description.md)
快速入门提供了一个含有两个页面的开发实例,并使用了不同的开发语言或不同的应用模型进行开发,以便开发者理解以上基本概念及应用开发流程。 快速入门提供了一个含有两个页面的开发实例,并基于Stage模型构建第一个ArkTS应用,以便开发者理解以上基本概念及应用开发流程。
## 工具准备 ## 工具准备
......
...@@ -837,6 +837,7 @@ type N = number ...@@ -837,6 +837,7 @@ type N = number
**级别:错误** **级别:错误**
ArkTS不支持通过索引访问对象的字段。改用点操作符。 ArkTS不支持通过索引访问对象的字段。改用点操作符。
ArkTS支持通过索引访问`TypedArray`(例如`Int32Array`)中的元素。
**TypeScript** **TypeScript**
...@@ -852,6 +853,9 @@ let x = p["x"] ...@@ -852,6 +853,9 @@ let x = p["x"]
class Point {x: number = 0; y: number = 0} class Point {x: number = 0; y: number = 0}
let p: Point = {x: 1, y: 2} let p: Point = {x: 1, y: 2}
let x = p.x let x = p.x
let arr = new Int32Array(1)
console.log(arr[0])
``` ```
### 不支持structural identity ### 不支持structural identity
...@@ -1305,7 +1309,7 @@ class Point { ...@@ -1305,7 +1309,7 @@ class Point {
y: number = 0 y: number = 0
// 在字面量初始化之前,使用constructor()创建一个有效对象。 // 在字面量初始化之前,使用constructor()创建一个有效对象。
// 由于Point没有其它构造函数,编译器将自动添加一个默认构造函数。 // 由于没有为Point定义构造函数,编译器将自动添加一个默认构造函数。
} }
function id_x_y(o: Point): Point { function id_x_y(o: Point): Point {
...@@ -1392,32 +1396,6 @@ let a2: C[] = [{n: 1, s: "1"}, {n: 2, s : "2"}] // a2的类型为“C[]” ...@@ -1392,32 +1396,6 @@ let a2: C[] = [{n: 1, s: "1"}, {n: 2, s : "2"}] // a2的类型为“C[]”
* 对象字面量必须对应某些显式声明的类或接口 * 对象字面量必须对应某些显式声明的类或接口
* 对象字面量不能用于类型声明 * 对象字面量不能用于类型声明
### 显式标注Lambda函数的参数类型
**规则:**`arkts-explicit-param-types-in-lambdas`
**级别:错误**
当前ArkTS要求显式标注lambda函数的参数的类型。
**TypeScript**
```typescript
// 只有在开启noImplicitAny选项时会产生编译时错误
let f = (s /* type any is assumed */) => {
console.log(s)
}
```
**ArkTS**
```typescript
// 显式标注Lambda函数的参数类型
let f = (s: string) => {
console.log(s)
}
```
### 使用箭头函数而非函数表达式 ### 使用箭头函数而非函数表达式
**规则:**`arkts-no-func-expressions` **规则:**`arkts-no-func-expressions`
...@@ -1814,9 +1792,9 @@ let f = "string" + true // "stringtrue" ...@@ -1814,9 +1792,9 @@ let f = "string" + true // "stringtrue"
let g = (new Object()) + "string" // "[object Object]string" let g = (new Object()) + "string" // "[object Object]string"
let i = true + true // JS: 2, TS: 编译时错误 let i = true + true // 编译时错误
let j = true + 2 // JS: 3, TS: 编译时错误 let j = true + 2 // 编译时错误
let k = E.E1 + true // JS: 1, TS: 编译时错误 let k = E.E1 + true // 编译时错误
``` ```
**ArkTS** **ArkTS**
...@@ -1835,7 +1813,7 @@ let f = "string" + true // "stringtrue" ...@@ -1835,7 +1813,7 @@ let f = "string" + true // "stringtrue"
let g = (new Object()).toString() + "string" let g = (new Object()).toString() + "string"
let i = true + true // 编译时错误 let i = true + true // 编译时错误
let j = true + 2 // 编译时错误 let j = true + 2 // 编译时错误
let k = E.E1 + true // 编译时错误 let k = E.E1 + true // 编译时错误
``` ```
...@@ -2142,7 +2120,7 @@ ArkTS不支持`Symbol`API、`Symbol.iterator`和最终可迭代的接口。请 ...@@ -2142,7 +2120,7 @@ ArkTS不支持`Symbol`API、`Symbol.iterator`和最终可迭代的接口。请
**级别:错误** **级别:错误**
ArkTS支持通过`for .. of`迭代数组和字符串,但不支持迭代对象。 ArkTS支持通过`for .. of`迭代数组、字符串和`TypedArray`(例如`Int32Array`,但不支持迭代对象。
**TypeScript** **TypeScript**
...@@ -2232,7 +2210,7 @@ console.log("Area: ", Math.PI * r * r) ...@@ -2232,7 +2210,7 @@ console.log("Area: ", Math.PI * r * r)
**级别:错误** **级别:错误**
在ArkTS中,`case`语句仅支持编译期值。若值无法在编译期确定,请使用`if`语句。 在ArkTS中,`case`语句仅支持编译期值,支持`const`常量和`class``static readonly`属性。若值无法在编译期确定,请使用`if`语句。
**TypeScript** **TypeScript**
...@@ -2689,7 +2667,7 @@ function main(): void { ...@@ -2689,7 +2667,7 @@ function main(): void {
**级别:错误** **级别:错误**
展开运算符唯一支持的场景是函数剩余参数为数组类型。 展开运算符唯一支持的场景是函数剩余参数为数组类型,包括`TypedArray`(例如`Int32Array`
**TypeScript** **TypeScript**
...@@ -3273,7 +3251,7 @@ import "path/to/module" ...@@ -3273,7 +3251,7 @@ import "path/to/module"
**ArkTS** **ArkTS**
```typescript ```typescript
import * from "path/to/module" import * as ns from "path/to/module"
``` ```
### 不支持`import default as ...` ### 不支持`import default as ...`
...@@ -3326,7 +3304,7 @@ import * as m from "mod" ...@@ -3326,7 +3304,7 @@ import * as m from "mod"
**级别:错误** **级别:错误**
ArkTS支持大多数场景下的重导出,比如命名导出和重命名导出,重导出import的。不支持`export * as ...` ArkTS支持大多数场景下的重导出,例如命名重导出和重命名重导出。不支持`export * as ...`
**TypeScript** **TypeScript**
...@@ -3512,7 +3490,7 @@ declare namespace N { ...@@ -3512,7 +3490,7 @@ declare namespace N {
function foo(x: number): number function foo(x: number): number
} }
import * from "module" import * as m from "module"
console.log("N.foo called: ", N.foo(42)) console.log("N.foo called: ", N.foo(42))
``` ```
...@@ -3622,32 +3600,6 @@ let ce = new CustomError() ...@@ -3622,32 +3600,6 @@ let ce = new CustomError()
* 不支持在原型上赋值 * 不支持在原型上赋值
### 不支持动态导入
**规则:**`arkts-no-runtime-import`
**级别:错误**
由于在ArkTS中,导入是编译时而非运行时特性,因此,ArkTS不支持动态导入,如`await import...`。改用静态`import`语法。
**TypeScript**
```typescript
const zipUtil = await import("utils/create-zip-file")
```
**ArkTS**
```typescript
import { zipUtil } from "utils/create-zip-file"
```
**相关约束**
* 不支持在模块名中使用通配符
* 不支持通用模块定义(UMD)
* 不支持导入断言
### 不支持确定赋值断言 ### 不支持确定赋值断言
**规则:**`arkts-no-definite-assignment` **规则:**`arkts-no-definite-assignment`
...@@ -3796,7 +3748,7 @@ M.abc = 200 ...@@ -3796,7 +3748,7 @@ M.abc = 200
**级别:错误** **级别:错误**
当前ArkTS不支持从TypeScript扩展到标准库的utility类型(例如`Omit``Pick`等)。支持`Partial``Record` ArkTS仅支持`Partial``Record`,不支持TypeScript中其他的`Utility Types`
对于*Record<K, V>*类型,表达式*rec[index]*的类型是*V | undefined* 对于*Record<K, V>*类型,表达式*rec[index]*的类型是*V | undefined*
对于`Record`类型,键-值中的值的类型必须是可选类型或者包含`undefined`的联合类型。 对于`Record`类型,键-值中的值的类型必须是可选类型或者包含`undefined`的联合类型。
...@@ -4079,9 +4031,7 @@ ArkTS不允许使用TypeScript或JavaScript标准库中的某些接口。大部 ...@@ -4079,9 +4031,7 @@ ArkTS不允许使用TypeScript或JavaScript标准库中的某些接口。大部
全局对象的属性和方法:`eval` 全局对象的属性和方法:`eval`
`Infinity``NaN``isFinite``isNaN``parseFloat``parseInt` `Infinity``NaN``isFinite``isNaN``parseFloat``parseInt`
`encodeURI``encodeURIComponent``Encode` `Encode``Decode``ParseHexOctet`
`decodeURI``decodeURIComponent``Decode`
`escape``unescape``ParseHexOctet`
`Object``__proto__``__defineGetter__``__defineSetter__` `Object``__proto__``__defineGetter__``__defineSetter__`
`__lookupGetter__``__lookupSetter__``assign``create` `__lookupGetter__``__lookupSetter__``assign``create`
...@@ -4267,3 +4217,52 @@ function classDecorator(x: number, y: number): void { ...@@ -4267,3 +4217,52 @@ function classDecorator(x: number, y: number): void {
class BugReport { class BugReport {
} }
``` ```
### `class`不能被用作对象
**规则:**`arkts-no-classes-as-obj`
**级别:错误**
在ArkTS中,`class`声明的是一个新的类型,不是一个值。因此,不支持将`class`用作对象(例如将`class`赋值给一个对象)。
**TypeScript**
```typescript
class C {
s: string = ""
n: number = 0
}
let c = C
```
### 不支持在`import`语句前使用其他语句
**规则:**`arkts-no-misplaced-imports`
**级别:错误**
在ArkTS中,除动态`import`语句外,所有`import`语句需要放在所有其他语句之前。
**TypeScript**
```typescript
class C {
s: string = ""
n: number = 0
}
import foo from "module1"
```
**ArkTS**
```typescript
import foo from "module1"
class C {
s: string = ""
n: number = 0
}
```
...@@ -66,12 +66,17 @@ import fs from '@ohos.file.fs'; ...@@ -66,12 +66,17 @@ import fs from '@ohos.file.fs';
try { try {
let fd = fs.openSync('/path/to/form.png'); let fd = fs.openSync('/path/to/form.png');
let obj = {
'temperature': '21°', let createFormBindingDataParam = new Map<Object, string | object>();
'formImages': { 'image': fd } let formImagesParam = new Map<Object, object>();
}; formImagesParam.set('image', fd);
formBindingData.createFormBindingData(obj); createFormBindingDataParam.set("name", '21°');
createFormBindingDataParam.set('formImages', formImagesParam);
formBindingData.createFormBindingData(createFormBindingDataParam);
} catch (error) { } catch (error) {
console.error(`catch error, code: ${error.code}, message: ${error.message}`); let code = (error as Base.BusinessError).code;
let message = (error as Base.BusinessError).message;
console.error(`catch error, code: ${code}, message: ${message}`);
} }
``` ```
\ No newline at end of file
...@@ -46,18 +46,19 @@ onAddForm(want: Want): formBindingData.FormBindingData ...@@ -46,18 +46,19 @@ onAddForm(want: Want): formBindingData.FormBindingData
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import Want from '@ohos.app.ability.Want';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm(want) { onAddForm(want: Want) {
console.log(`FormExtensionAbility onAddForm, want: ${want.abilityName}`); console.log(`FormExtensionAbility onAddForm, want: ${want.abilityName}`);
let dataObj1 = { let dataObj1 = new Map<Object, string>();
temperature: '11c', dataObj1.set('temperature', '11c');
'time': '11:00' dataObj1.set('time', '11:00');
};
let obj1 = formBindingData.createFormBindingData(dataObj1); let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1; return obj1;
} }
}; }
``` ```
## onCastToNormalForm ## onCastToNormalForm
...@@ -80,7 +81,7 @@ onCastToNormalForm(formId: string): void ...@@ -80,7 +81,7 @@ onCastToNormalForm(formId: string): void
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onCastToNormalForm(formId) { onCastToNormalForm(formId: string) {
console.log(`FormExtensionAbility onCastToNormalForm, formId: ${formId}`); console.log(`FormExtensionAbility onCastToNormalForm, formId: ${formId}`);
} }
}; };
...@@ -108,16 +109,18 @@ import formBindingData from '@ohos.app.form.formBindingData'; ...@@ -108,16 +109,18 @@ import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onUpdateForm(formId) { onUpdateForm(formId: string) {
console.log(`FormExtensionAbility onUpdateForm, formId: ${formId}`); console.log(`FormExtensionAbility onUpdateForm, formId: ${formId}`);
class createFormBindingDataParam {
temperature: string
time: string
}
let obj2 = formBindingData.createFormBindingData({ let obj2 = formBindingData.createFormBindingData({
temperature: '22c', temperature: '22c',
time: '22:00' time: '22:00'
}); } as createFormBindingDataParam);
formProvider.updateForm(formId, obj2).then((data) => { formProvider.updateForm(formId, obj2).then((data) => {
console.log(`FormExtensionAbility context updateForm, data: ${data}`); console.log(`FormExtensionAbility context updateForm, data: ${data}`);
}).catch((error) => {
console.error(`Operation updateForm failed. Cause: ${error}`);
}); });
} }
}; };
...@@ -144,13 +147,24 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; ...@@ -144,13 +147,24 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider'; import formProvider from '@ohos.app.form.formProvider';
// 由于arkTs中无Object.keys,且无法使用for..in...
// 若报arkTs问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用
function getObjKeys(obj: Object): string[] {
let keys = Object.keys(obj);
return keys;
}
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onChangeFormVisibility(newStatus) { onChangeFormVisibility(newStatus) {
console.log(`FormExtensionAbility onChangeFormVisibility, newStatus: ${newStatus}`); console.log(`FormExtensionAbility onChangeFormVisibility, newStatus: ${newStatus}`);
class createFormBindingDataParam {
temperature: string
time: string
}
let obj2 = formBindingData.createFormBindingData({ let obj2 = formBindingData.createFormBindingData({
temperature: '22c', temperature: '22c',
time: '22:00' time: '22:00'
}); } as createFormBindingDataParam);
for (let key in newStatus) { for (let key in newStatus) {
console.log(`FormExtensionAbility onChangeFormVisibility, key: ${key}, value= ${newStatus[key]}`); console.log(`FormExtensionAbility onChangeFormVisibility, key: ${key}, value= ${newStatus[key]}`);
...@@ -185,7 +199,7 @@ onFormEvent(formId: string, message: string): void ...@@ -185,7 +199,7 @@ onFormEvent(formId: string, message: string): void
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) { onFormEvent(formId: string, message: string) {
console.log(`FormExtensionAbility onFormEvent, formId: ${formId}, message: ${message}`); console.log(`FormExtensionAbility onFormEvent, formId: ${formId}, message: ${message}`);
} }
}; };
...@@ -211,7 +225,7 @@ onRemoveForm(formId: string): void ...@@ -211,7 +225,7 @@ onRemoveForm(formId: string): void
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onRemoveForm(formId) { onRemoveForm(formId: string) {
console.log(`FormExtensionAbility onRemoveForm, formId: ${formId}`); console.log(`FormExtensionAbility onRemoveForm, formId: ${formId}`);
} }
}; };
...@@ -235,9 +249,10 @@ onConfigurationUpdate(newConfig: Configuration): void; ...@@ -235,9 +249,10 @@ onConfigurationUpdate(newConfig: Configuration): void;
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import { Configuration } from '@ohos.app.ability.Configuration';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onConfigurationUpdate(config) { onConfigurationUpdate(config: Configuration) {
console.log(`onConfigurationUpdate, config: ${JSON.stringify(config)}`); console.log(`onConfigurationUpdate, config: ${JSON.stringify(config)}`);
} }
}; };
...@@ -262,9 +277,10 @@ onAcquireFormState?(want: Want): formInfo.FormState; ...@@ -262,9 +277,10 @@ onAcquireFormState?(want: Want): formInfo.FormState;
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formInfo from '@ohos.app.form.formInfo'; import formInfo from '@ohos.app.form.formInfo';
import Want from '@ohos.app.ability.Want';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormState(want) { onAcquireFormState(want: Want) {
console.log(`FormExtensionAbility onAcquireFormState, want: ${want}`); console.log(`FormExtensionAbility onAcquireFormState, want: ${want}`);
return formInfo.FormState.UNKNOWN; return formInfo.FormState.UNKNOWN;
} }
...@@ -299,11 +315,11 @@ onShareForm?(formId: string): { [key: string]: Object } ...@@ -299,11 +315,11 @@ onShareForm?(formId: string): { [key: string]: Object }
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onShareForm(formId) { onShareForm(formId: string) {
console.log(`FormExtensionAbility onShareForm, formId: ${formId}`); console.log(`FormExtensionAbility onShareForm, formId: ${formId}`);
let wantParams = { let wantParams = {
'temperature': '20', 'temperature': '20',
'time': '2022-8-8 09:59', 'time': '2022-8-8 09:59',s
}; };
return wantParams; return wantParams;
} }
...@@ -338,7 +354,7 @@ onAcquireFormData?(formId: string): { [key: string]: Object } ...@@ -338,7 +354,7 @@ onAcquireFormData?(formId: string): { [key: string]: Object }
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormData(formId) { onAcquireFormData(formId: string) {
console.log('FormExtensionAbility onAcquireFormData, formId: ${formId}'); console.log('FormExtensionAbility onAcquireFormData, formId: ${formId}');
let wantParams = { let wantParams = {
'temperature': '20', 'temperature': '20',
......
...@@ -17,7 +17,7 @@ import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawa ...@@ -17,7 +17,7 @@ import { DrawableDescriptor, LayeredDrawableDescriptor } from '@ohos.arkui.drawa
## DrawableDescriptor.constructor ## DrawableDescriptor.constructor
constructor() constructor()
创建DrawableDescriptor或LayeredDrawableDescriptor对象。对象构造需要使用全球化接口[getDrawableDescriptor](js-apis-resource-manager.md##getdrawabledescriptor)[getDrawableDescriptorByName](js-apis-resource-manager.md##getdrawabledescriptorbyname) 创建DrawableDescriptor或LayeredDrawableDescriptor对象。对象构造需要使用全球化接口[getDrawableDescriptor](js-apis-resource-manager.md#getdrawabledescriptor)[getDrawableDescriptorByName](js-apis-resource-manager.md#getdrawabledescriptorbyname)
**系统接口:** 此接口为系统接口。 **系统接口:** 此接口为系统接口。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册