• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2021-2022 Huawei Device 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 UIAbility from '@ohos.app.ability.UIAbility';
17import bundleManager from '@ohos.bundle.bundleManager';
18import bundleMonitor from '@ohos.bundle.bundleMonitor';
19import account_osAccount from '@ohos.account.osAccount';
20import { GlobalContext } from '../common/utils/globalContext';
21
22const TAG = 'PermissionManager_MainAbility:';
23const USER_ID = 100;
24
25export default class MainAbility extends UIAbility {
26  onCreate(want, launchParam): void {
27    console.log(TAG + 'MainAbility onCreate, ability name is ' + want.abilityName + '.');
28
29    globalThis.bundleName = want.parameters.bundleName;
30    GlobalContext.store('bundleName', want.parameters.bundleName);
31    GlobalContext.store('context', this.context);
32  }
33
34  onWindowStageCreate(windowStage): void {
35    // Main window is created, set main page for this ability
36    console.log(TAG + 'MainAbility onWindowStageCreate.');
37    globalThis.windowStage = windowStage;
38    globalThis.refresh = false;
39
40    if (globalThis.bundleName) {
41      globalThis.currentApp = globalThis.bundleName;
42      this.getSperifiedApplication(globalThis.bundleName);
43    } else {
44      globalThis.currentApp = 'all';
45      this.getAllApplications();
46    }
47    bundleMonitor.on('add', (bundleChangeInfo) => {
48      console.log(`${TAG} bundleMonitor.add: ${JSON.stringify(bundleChangeInfo)}`);
49      if (globalThis.currentApp === 'all') {
50        this.getAllApplications();
51        globalThis.refresh = true;
52      }
53    })
54    bundleMonitor.on('remove', (bundleChangeInfo) => {
55      console.log(`${TAG} bundleMonitor.remove: ${JSON.stringify(bundleChangeInfo)}`);
56      if (globalThis.currentApp === 'all') {
57        this.getAllApplications();
58        globalThis.refresh = true;
59      }
60    })
61  }
62
63  onNewWant(want): void {
64    console.log(TAG + 'MainAbility onNewWant. want: ' + JSON.stringify(want));
65    console.log(TAG + 'MainAbility onNewWant. bundleName: ' + JSON.stringify(want.parameters.bundleName));
66
67    let bundleName = want.parameters.bundleName ? want.parameters.bundleName : 'all';
68    if (globalThis.currentApp === 'all') {
69      if (globalThis.currentApp !== bundleName) {
70        console.log(TAG + 'MainAbility onNewWant. all -> app');
71        globalThis.windowStage.setUIContent(this.context, 'pages/transition', null);
72        globalThis.currentApp = bundleName;
73        GlobalContext.store('bundleName', bundleName);
74        this.getSperifiedApplication(bundleName);
75      } else {
76        if (globalThis.refresh === true) {
77          globalThis.windowStage.setUIContent(this.context, 'pages/transition', null);
78          this.getAllApplications();
79          globalThis.refresh = false;
80        }
81      }
82    } else {
83      if (bundleName === 'all') {
84        console.log(TAG + 'MainAbility onNewWant. app -> all');
85        globalThis.windowStage.setUIContent(this.context, 'pages/transition', null);
86        globalThis.currentApp = 'all';
87        this.getAllApplications();
88      } else {
89        if (globalThis.currentApp !== bundleName) {
90          console.log(TAG + 'MainAbility onNewWant. app -> app');
91          globalThis.windowStage.setUIContent(this.context, 'pages/transition', null);
92          globalThis.currentApp = bundleName;
93          GlobalContext.store('bundleName', bundleName);
94          this.getSperifiedApplication(bundleName);
95        }
96      }
97    }
98
99  }
100
101  onWindowStageDestroy(): void {
102    bundleMonitor.off('add');
103    bundleMonitor.off('remove');
104    console.log(TAG + 'MainAbility onWindowStageDestroy.');
105  }
106
107  onBackground(): void {
108    console.log(TAG + ' onBackground.');
109  }
110
111  onDestroy(): void {
112    console.log(TAG + ' onDestroy.');
113  }
114
115  onForeground(): void {
116    console.log(TAG + ' onForeground.');
117  }
118
119  getAllApplications(): void {
120    const flag = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
121    let accountManager = account_osAccount.getAccountManager();
122    try {
123      accountManager.getActivatedOsAccountLocalIds((err, idArray: number[])=>{
124        console.log(TAG + 'getActivatedOsAccountLocalIds err:' + JSON.stringify(err));
125        console.log(TAG + 'getActivatedOsAccountLocalIds idArray: ' + JSON.stringify(idArray));
126        let userId = idArray[0];
127        bundleManager.getAllBundleInfo(flag, userId || USER_ID).then(async(bundleInfos) => {
128          if (bundleInfos.length <= 0) {
129            console.info(TAG + 'bundle.getAllBundleInfo result.length less than or equal to zero');
130            return;
131          }
132          let initialGroups = [];
133          for (let i = 0; i < bundleInfos.length; i++) {
134            let info = bundleInfos[i];
135            // Filter blank icon icon and text label resources
136            try {
137              await bundleManager.queryAbilityInfo({
138                bundleName: info.name,
139                action: 'action.system.home',
140                entities: ['entity.system.home']
141              }, bundleManager.AbilityFlag.GET_ABILITY_INFO_WITH_APPLICATION);
142            } catch (error) {
143              console.error(TAG + 'queryAbilityByWant catch app: ' + JSON.stringify(info.name) + 'err: ' + JSON.stringify(error));
144              continue;
145            }
146
147            initialGroups.push(info);
148          }
149          let storage: LocalStorage = new LocalStorage({ 'initialGroups': initialGroups });
150          globalThis.windowStage.loadContent('pages/authority-management', storage);
151        }).catch((error) => {
152          console.error(TAG + 'bundle.getAllBundleInfo failed. Cause: ' + JSON.stringify(error));
153        });
154      });
155    } catch (e) {
156      console.error(TAG + 'getActivatedOsAccountLocalIds exception: ' + JSON.stringify(e));
157    }
158  }
159
160  getSperifiedApplication(bundleName): void {
161    const flag = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
162    bundleManager.getBundleInfo(bundleName, flag).then(bundleInfo => {
163      let reqPermissions: Array<string> = [];
164      bundleInfo.reqPermissionDetails.forEach(item => {
165        reqPermissions.push(item.name);
166      });
167
168      let info = {
169        'bundleName': bundleInfo.name,
170        'api': bundleInfo.targetVersion,
171        'tokenId': bundleInfo.appInfo.accessTokenId,
172        'icon': '',
173        'iconId': bundleInfo.appInfo.iconId,
174        'iconResource': bundleInfo.appInfo.iconResource,
175        'label': '',
176        'labelId': bundleInfo.appInfo.labelId,
177        'labelResource': bundleInfo.appInfo.labelResource,
178        'permissions': reqPermissions,
179        'groupId': [],
180        'zhTag': '',
181        'indexTag': '',
182        'language': ''
183      };
184      GlobalContext.store('applicationInfo', info);
185      globalThis.windowStage.setUIContent(this.context, 'pages/application-secondary', null);
186    }).catch(() => {
187      console.log(TAG + 'MainAbility getSperifiedApplication failed.');
188      this.context.terminateSelf();
189    });
190  }
191};
192