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