• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.LOCATION',
25  'ohos.permission.APPROXIMATELY_LOCATION'
26];
27
28export default async function grantPermission(): Promise<boolean> {
29  try {
30    // 获取应用程序的accessTokenID
31    let bundleInfo: bundleManager.BundleInfo =
32      await bundleManager.getBundleInfoForSelf(
33        bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
34      );
35    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
36    let tokenId = appInfo.accessTokenId;
37
38    let atManager = abilityAccessCtrl.createAtManager();
39    let pems: Array<Permissions> = [];
40
41    for (let i = 0; i < PERMISSIONS.length; i++) {
42      let state = await atManager.checkAccessToken(tokenId, PERMISSIONS[i]);
43      Logger.info(TAG, `grantPermission  checkAccessToken ${PERMISSIONS[i]} + : ${JSON.stringify(state)}`);
44      if (state !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
45        pems.push(PERMISSIONS[i]);
46      }
47    }
48    if (pems.length > 0) {
49      Logger.info(TAG, 'grantPermission  requestPermissionsFromUser :' + JSON.stringify(pems));
50      let result = await atManager.requestPermissionsFromUser(AppStorage.get('abilityContext')!, pems);
51
52      let grantStatus: Array<number> = result.authResults;
53      let length: number = grantStatus.length;
54      for (let i = 0; i < length; i++) {
55        Logger.info(TAG, `grantPermission  requestPermissionsFromUser ${result.permissions[i]} + : ${grantStatus[i]}`);
56
57        if (grantStatus[i] === 0) {
58          // 用户授权,可以继续访问目标操作
59        } else {
60          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能
61          console.log(TAG + 'grantPermission  fail ');
62          return false;
63        }
64      }
65    }
66    // 授权成功
67    Logger.info(TAG, 'grantPermission  success ');
68    return true;
69  } catch (e) {
70    Logger.info(TAG, 'grantPermission  fail ');
71    return false;
72  }
73}
74