• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 相机启动恢复实践(ArkTS)
2<!--Kit: Camera Kit-->
3<!--Subsystem: Multimedia-->
4<!--Owner: @qano-->
5<!--Designer: @leo_ysl-->
6<!--Tester: @xchaosioda-->
7<!--Adviser: @zengyawen-->
8
9当前示例提供完整的相机应用从后台切换至前台启动恢复的流程介绍,方便开发者了解完整的接口调用顺序。
10
11相机应用在前后台切换过程中的状态变化说明:
12- 当相机应用在退后台之后由于安全策略会被强制断流,并且此时相机状态回调会返回相机可用状态,表示当前相机设备已经被关闭,处于空闲状态。
13- 当相机应用从后台切换至前台时,相机状态回调会返回相机不可用状态,表示当前相机设备被打开,处于忙碌状态。
14- 相机应用从后台切换至前台时,需要重启相机设备的预览流、拍照流以及相机会话管理。
15
16在参考以下示例前,建议开发者查看[相机开发指导(ArkTS)](camera-device-management.md)的具体章节,了解[相机管理](camera-device-management.md)、[设备输入](camera-device-input.md)、[会话管理](camera-session-management.md)等单个操作。
17
18## 开发流程
19
20相机应用从后台切换至前台启动恢复的调用流程建议如下:
21
22![Camera Background recovery processing](figures/camera-background-recovery.png)
23
24## 完整示例
25
26Context获取方式请参考:[获取UIAbility的上下文信息](../../application-models/uiability-usage.md#获取uiability的上下文信息)。
27
28相机应用从后台切换至前台启动恢复需要在页面生命周期回调函数onPageShow中调用,重新初始化相机设备。
29
30   ```ts
31   import { camera } from '@kit.CameraKit';
32   import { BusinessError } from '@kit.BasicServicesKit';
33   import { common } from '@kit.AbilityKit';
34
35   let context: common.BaseContext;
36   let surfaceId: string = '';
37   async function onPageShow(): Promise<void> {
38      // 当应用从后台切换至前台页面显示时,重新初始化相机设备。
39      await initCamera(context, surfaceId);
40   }
41
42   async function initCamera(baseContext: common.BaseContext, surfaceId: string): Promise<void> {
43      console.info('onForeGround recovery begin.');
44      let cameraManager: camera.CameraManager = camera.getCameraManager(baseContext);
45      if (!cameraManager) {
46        console.error("camera.getCameraManager error");
47        return;
48      }
49      // 监听相机状态变化。
50      cameraManager.on('cameraStatus', (err: BusinessError, cameraStatusInfo: camera.CameraStatusInfo) => {
51          if (err !== undefined && err.code !== 0) {
52            console.error('cameraStatus with errorCode = ' + err.code);
53            return;
54          }
55          console.info(`camera : ${cameraStatusInfo.camera.cameraId}`);
56          console.info(`status: ${cameraStatusInfo.status}`);
57        });
58
59      // 获取相机列表。
60      let cameraArray: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
61      if (cameraArray.length <= 0) {
62        console.error("cameraManager.getSupportedCameras error");
63        return;
64      }
65
66      for (let index = 0; index < cameraArray.length; index++) {
67        console.info('cameraId : ' + cameraArray[index].cameraId);                       // 获取相机ID。
68        console.info('cameraPosition : ' + cameraArray[index].cameraPosition);           // 获取相机位置。
69        console.info('cameraType : ' + cameraArray[index].cameraType);                   // 获取相机类型。
70        console.info('connectionType : ' + cameraArray[index].connectionType);           // 获取相机连接类型。
71      }
72
73      // 创建相机输入流。
74      let cameraInput: camera.CameraInput | undefined = undefined;
75      try {
76        cameraInput = cameraManager.createCameraInput(cameraArray[0]);
77      } catch (error) {
78          let err = error as BusinessError;
79          console.error('Failed to createCameraInput errorCode = ' + err.code);
80      }
81      if (cameraInput === undefined) {
82        return;
83      }
84
85      // 监听cameraInput错误信息。
86      let cameraDevice: camera.CameraDevice = cameraArray[0];
87        cameraInput.on('error', cameraDevice, (error: BusinessError) => {
88        console.error(`Camera input error code: ${error.code}`);
89      });
90
91      // 打开相机。
92      await cameraInput.open();
93
94      // 获取支持的模式类型。
95      let sceneModes: Array<camera.SceneMode> = cameraManager.getSupportedSceneModes(cameraArray[0]);
96      let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;
97      if (!isSupportPhotoMode) {
98        console.error('photo mode not support');
99        return;
100      }
101      // 获取相机设备支持的输出流能力。
102      let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO);
103      if (!cameraOutputCap) {
104        console.error("cameraManager.getSupportedOutputCapability error");
105        return;
106      }
107      console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
108
109      let previewProfilesArray: Array<camera.Profile> = cameraOutputCap.previewProfiles;
110      if (!previewProfilesArray) {
111        console.error("createOutput previewProfilesArray is null!");
112        return;
113      }
114
115      let photoProfilesArray: Array<camera.Profile> = cameraOutputCap.photoProfiles;
116      if (!photoProfilesArray) {
117        console.error("createOutput photoProfilesArray is null!");
118        return;
119      }
120
121      // 创建预览输出流,其中参数surfaceId参考上文XComponent组件,预览流为XComponent组件提供的surface。
122      let previewOutput: camera.PreviewOutput | undefined = undefined;
123      try {
124        previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId);
125      } catch (error) {
126        let err = error as BusinessError;
127        console.error(`Failed to create the PreviewOutput instance. error code: ${err.code}`);
128      }
129      if (previewOutput === undefined) {
130        return;
131      }
132      // 监听预览输出错误信息。
133      previewOutput.on('error', (error: BusinessError) => {
134        console.error(`Preview output error code: ${error.code}`);
135      });
136
137      // 创建拍照输出流。
138      let photoOutput: camera.PhotoOutput | undefined = undefined;
139      try {
140        photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0]);
141      } catch (error) {
142          let err = error as BusinessError;
143          console.error('Failed to createPhotoOutput errorCode = ' + err.code);
144      }
145      if (photoOutput === undefined) {
146        return;
147      }
148
149      //创建会话。
150      let photoSession: camera.PhotoSession | undefined = undefined;
151      try {
152        photoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;
153      } catch (error) {
154          let err = error as BusinessError;
155          console.error('Failed to create the session instance. errorCode = ' + err.code);
156      }
157      if (photoSession === undefined) {
158        return;
159      }
160      // 监听session错误信息。
161      photoSession.on('error', (error: BusinessError) => {
162        console.error(`Capture session error code: ${error.code}`);
163      });
164
165      // 开始配置会话。
166      try {
167        photoSession.beginConfig();
168      } catch (error) {
169          let err = error as BusinessError;
170          console.error('Failed to beginConfig. errorCode = ' + err.code);
171      }
172
173      // 向会话中添加相机输入流。
174      try {
175        photoSession.addInput(cameraInput);
176      } catch (error) {
177          let err = error as BusinessError;
178          console.error('Failed to addInput. errorCode = ' + err.code);
179      }
180
181      // 向会话中添加预览输出流。
182      try {
183        photoSession.addOutput(previewOutput);
184      } catch (error) {
185          let err = error as BusinessError;
186          console.error('Failed to addOutput(previewOutput). errorCode = ' + err.code);
187      }
188
189      // 向会话中添加拍照输出流。
190      try {
191        photoSession.addOutput(photoOutput);
192      } catch (error) {
193          let err = error as BusinessError;
194          console.error('Failed to addOutput(photoOutput). errorCode = ' + err.code);
195      }
196
197      // 提交会话配置。
198      await photoSession.commitConfig();
199
200      // 启动会话。
201      await photoSession.start().then(() => {
202        console.info('Promise returned to indicate the session start success.');
203      });
204      // 判断设备是否支持闪光灯。
205      let flashStatus: boolean = false;
206        try {
207          flashStatus = photoSession.hasFlash();
208      } catch (error) {
209          let err = error as BusinessError;
210          console.error('Failed to hasFlash. errorCode = ' + err.code);
211      }
212      console.info('Returned with the flash light support status:' + flashStatus);
213
214      if (flashStatus) {
215        // 判断是否支持自动闪光灯模式。
216        let flashModeStatus: boolean = false;
217        try {
218          let status: boolean = photoSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
219          flashModeStatus = status;
220        } catch (error) {
221            let err = error as BusinessError;
222            console.error('Failed to check whether the flash mode is supported. errorCode = ' + err.code);
223        }
224        if(flashModeStatus) {
225          // 设置自动闪光灯模式。
226          try {
227            photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
228          } catch (error) {
229              let err = error as BusinessError;
230              console.error('Failed to set the flash mode. errorCode = ' + err.code);
231          }
232        }
233      }
234
235      // 判断是否支持连续自动变焦模式。
236      let focusModeStatus: boolean = false;
237      try {
238        let status: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
239        focusModeStatus = status;
240      } catch (error) {
241          let err = error as BusinessError;
242          console.error('Failed to check whether the focus mode is supported. errorCode = ' + err.code);
243      }
244
245      if (focusModeStatus) {
246        // 设置连续自动变焦模式。
247        try {
248          photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);
249        } catch (error) {
250            let err = error as BusinessError;
251            console.error('Failed to set the focus mode. errorCode = ' + err.code);
252        }
253      }
254
255      // 获取相机支持的可变焦距比范围。
256      let zoomRatioRange: Array<number> = [];
257      try {
258        zoomRatioRange = photoSession.getZoomRatioRange();
259      } catch (error) {
260          let err = error as BusinessError;
261          console.error('Failed to get the zoom ratio range. errorCode = ' + err.code);
262      }
263      if (zoomRatioRange.length <= 0) {
264        return;
265      }
266      // 设置可变焦距比。
267      try {
268        photoSession.setZoomRatio(zoomRatioRange[0]);
269      } catch (error) {
270          let err = error as BusinessError;
271          console.error('Failed to set the zoom ratio value. errorCode = ' + err.code);
272      }
273      let photoCaptureSetting: camera.PhotoCaptureSetting = {
274        quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // 设置图片质量高。
275        rotation: camera.ImageRotation.ROTATION_0 // 设置图片旋转角度0。
276      }
277      // 使用当前拍照设置进行拍照。
278      photoOutput.capture(photoCaptureSetting, (err: BusinessError) => {
279        if (err) {
280          console.error(`Failed to capture the photo ${err.message}`);
281          return;
282        }
283        console.info('Callback invoked to indicate the photo capture request success.');
284      });
285
286      console.info('onForeGround recovery end.');
287   }
288   ```