• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 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 AbilityConstant from '@ohos.app.ability.AbilityConstant'
18import accessControl, { Permissions } from "@ohos.abilityAccessCtrl";
19import bundle from '@ohos.bundle';
20import distributedObject from '@ohos.data.distributedDataObject';
21import Logger from './Logger';
22import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
23import bundleManager from '@ohos.bundle.bundleManager';
24import window from '@ohos.window';
25
26const BUNDLE_NAME = "com.ohos.continuationManualTestSuite.hmservice"
27const PERMISSION_REJECT = -1
28
29class ContentStorage {
30}
31
32
33export default class MainAbility extends UIAbility {
34
35    contentStorage : LocalStorage
36    sessionId : string
37    g_object: distributedObject.DataObject|null = null;
38
39    async handleParam(want) {
40        this.g_object = distributedObject.create(this.context, {data:undefined});
41        if (this.g_object) {
42            this.g_object = undefined;
43        }
44        if (!this.g_object) {
45            this.g_object = distributedObject.create(this.context, {name: undefined});
46        }
47        this.sessionId = want.parameters.session
48        Logger.info(`continuation sessionId:  ${this.sessionId}`)
49
50
51        await this.g_object.setSessionId(this.sessionId); // set session id, so it will sync data from remote device
52        Logger.info(`this.g_object_name = ${this.g_object['name']}`);
53
54        AppStorage.setOrCreate<string>('ContinueStudy', this.g_object['name'])
55        let workInput = want.parameters.work // get user data from want params
56        Logger.info(`work input ${workInput}`)
57        AppStorage.setOrCreate<string>('ContinueWork', workInput)
58        this.contentStorage = new LocalStorage();
59        Logger.info('ready to restore');
60        this.context.restoreWindowStage(this.contentStorage);
61    }
62
63    onCreate(want, launchParam: AbilityConstant.LaunchParam) {
64        Logger.info("[Demo] MainAbility onCreate")
65        if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
66            this.handleParam(want);
67        }
68    }
69
70    onContinue(wantParam : {[key: string]: any}) {
71        Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
72        let workInput = AppStorage.get<string>('ContinueWork');
73        Logger.info(`onContinue work input = ${workInput}`);
74        if (this.g_object) {
75            this.g_object = undefined;
76        }
77        this.g_object = distributedObject.create(this.context, {name: undefined});
78
79        this.sessionId = distributedObject.genSessionId();
80        wantParam['session'] = this.sessionId;
81        if (this.g_object != null) {
82            // 分布式对象设置 sessionId
83            this.g_object.setSessionId(this.sessionId, () => {
84                Logger.info("join session");
85            })
86        }
87        this.g_object['name'] = AppStorage.get<string>('ContinueStudy');
88        Logger.info(`onContinue sessionId = ${this.sessionId}, name = ${this.g_object['name']}`)
89        this.g_object.save(wantParam.targetDevice, (err, result)=>{
90            if (err) {
91                Logger.info(" save callback err: ", JSON.stringify(err));
92                return;
93            }
94            Logger.info('save callback,result = ', JSON.stringify(result));
95        });
96        wantParam["work"] = workInput // set user input data into want params
97        return 0;
98    }
99
100    onNewWant(want, launchParam) {
101        Logger.info("MainAbility onNewWant")
102        if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
103            this.handleParam(want);
104        }
105    }
106
107    //获取当前应用的权限的授予状态:grantStatus(授予返回:0,未授予:-1)
108    async getGrantStatus(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus>{
109        let atManager = abilityAccessCtrl.createAtManager();
110        let grantStatus : abilityAccessCtrl.GrantStatus = -1;
111
112        //获取tokenId:
113        let tokenId :number = 0;
114        try {
115            let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
116            let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
117            tokenId = appInfo.accessTokenId;
118        }catch (err){
119            Logger.info('Failed to get bundle info for self,cause ${public}s' ,JSON.stringify(err)??'');
120        }
121
122        // 检验应用是否被授予此权限,授予返回:PERMISSION_GRANTED = 0,未授予:PERMISSION_DENIED = -1
123        try {
124            grantStatus = await atManager.checkAccessToken(tokenId,permission);
125        }catch (err){
126            Logger.info('Failed to check Access Token ,cause %{public}s' ,JSON.stringify(err)??'');
127        }
128
129        return grantStatus;
130    }
131
132    //检验权限授予情况&动态申请权限
133    async checkPermissions():Promise<void>{
134        const permissions:Array<Permissions> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
135
136        let grantStatus:abilityAccessCtrl.GrantStatus = await this.getGrantStatus(permissions[0]);
137        // 检验权限授予情况
138        if(grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED){
139            //已授予
140            Logger.info('Permission already granted.');
141        }else{
142            //未授予,向用户弹框动态申请授权
143            let atManager = abilityAccessCtrl.createAtManager();
144            try {
145                atManager.requestPermissionsFromUser(this.context, ['ohos.permission.DISTRIBUTED_DATASYNC'], (err, data) => {
146                    Logger.info('data: ' + JSON.stringify(data));
147                });
148            }catch (err){
149                Logger.info('catch err ,' + JSON.stringify(err)??'');
150                return;
151            }
152        }
153    }
154
155    onDestroy() {
156        Logger.info("MainAbility onDestroy")
157    }
158
159    onWindowStageCreate(windowStage: window.WindowStage) {
160        // Main window is created, set main page for this ability
161        Logger.info("MainAbility onWindowStageCreate");
162        this.checkPermissions()
163        windowStage.loadContent('pages/Index', (err, data) => {
164            if (err.code) {
165                Logger.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
166                return;
167            }
168            Logger.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
169        });
170    }
171
172    onWindowStageRestore(windowStage: window.WindowStage) {
173        Logger.info("MainAbility onWindowStageRestore");
174        this.checkPermissions();
175    }
176
177    onWindowStageDestroy() {
178        // Main window is destroyed, release UI related resources
179        Logger.info("MainAbility onWindowStageDestroy")
180    }
181
182    onForeground() {
183        // Ability has brought to foreground
184        Logger.info("MainAbility onForeground")
185    }
186
187    onBackground() {
188        // Ability has back to background
189        Logger.info("MainAbility onBackground")
190    }
191};
192