1/* 2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; 17import { Permissions } from '@ohos.abilityAccessCtrl'; 18import bundleManager from '@ohos.bundle.bundleManager'; 19import Logger from './Logger'; 20 21const TAG: string = '[Permission]'; 22 23const PERMISSIONS: Array<Permissions> = [ 24 'ohos.permission.CAMERA' 25]; 26 27export default async function grantPermission(): Promise<boolean> { 28 try { 29 // 获取应用程序的accessTokenID 30 let bundleInfo: bundleManager.BundleInfo = 31 await bundleManager.getBundleInfoForSelf( 32 bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION 33 ); 34 let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo; 35 let tokenId = appInfo.accessTokenId; 36 37 let atManager = abilityAccessCtrl.createAtManager(); 38 let pems: Array<Permissions> = []; 39 40 for (let i = 0; i < PERMISSIONS.length; i++) { 41 let state = await atManager.checkAccessToken(tokenId, PERMISSIONS[i]); 42 Logger.info(TAG, `grantPermission checkAccessToken ${PERMISSIONS[i]} + : ${JSON.stringify(state)}`); 43 if (state !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { 44 pems.push(PERMISSIONS[i]); 45 } 46 } 47 if (pems.length > 0) { 48 Logger.info(TAG, 'grantPermission requestPermissionsFromUser :' + JSON.stringify(pems)); 49 let result = await atManager.requestPermissionsFromUser(AppStorage.get('cameraContext')!, pems); 50 51 let grantStatus: Array<number> = result.authResults; 52 let length: number = grantStatus.length; 53 for (let i = 0; i < length; i++) { 54 Logger.info(TAG, `grantPermission requestPermissionsFromUser ${result.permissions[i]} + : ${grantStatus[i]}`); 55 56 if (grantStatus[i] === 0) { 57 // 用户授权,可以继续访问目标操作 58 } else { 59 // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能 60 console.log(TAG + 'grantPermission fail '); 61 return false; 62 } 63 } 64 } 65 // 授权成功 66 Logger.info(TAG, 'grantPermission success '); 67 return true; 68 } catch (e) { 69 Logger.info(TAG, 'grantPermission fail '); 70 return false; 71 } 72} 73