• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024 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 common from '@ohos.app.ability.common';
17import commonEvent from '@ohos.commonEventManager';
18import dataPreferences from '@ohos.data.preferences';
19import Want from '@ohos.app.ability.Want';
20import router from '@ohos.router';
21import consts from '../module/Consts';
22import Logger from '../module/Logger';
23
24export default class LaunchFeature {
25  private innerContext: common.UIAbilityContext = null;
26  private pref: dataPreferences.Preferences = null;
27  private subscriber = null;
28  private subscriberLow = null;
29  private currentRecordTimes: number = 0;
30
31  constructor(abilityContext: common.UIAbilityContext) {
32    this.innerContext = abilityContext;
33  }
34
35  async init(): Promise<void> {
36    await dataPreferences.getPreferences(this.innerContext, consts.DATA_BASE_NAME).then((pref) => {
37      this.pref = pref;
38    });
39    await this.pref.get(consts.DATA_BASE_KEY_WIFI_POWER_STATE, 0).then((value: number) => {
40      globalThis.settings.set(commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE, value);
41    });
42    await this.pref.get(consts.DATA_BASE_KEY_SCREEN_OFF, 0).then((value1: number) => {
43      globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_OFF, value1);
44    });
45    await this.pref.get(consts.DATA_BASE_KEY_SCREEN_ON, 0).then((value2: number) => {
46      globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_ON, value2);
47    });
48    await this.pref.get(consts.DATA_BASE_KEY_SCREEN_LOCKED, 0).then((value3: number) => {
49      globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED, value3);
50    });
51    await this.pref.get(consts.DATA_BASE_KEY_SCREEN_UNLOCKED, 0).then((value4: number) => {
52      globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED, value4);
53    });
54  }
55
56  private insertRecord = (event, value) => {
57    value.push(event.parameters[consts.DATA_BASE_KEY_START_TIME]);
58    // refresh database
59    this.pref.put(consts.DATA_BASE_KEY_TOTAL_TIMES, value).then(() => {
60      let detail: Array<string> = [];
61      detail.push(event.parameters["startTime"]);
62      detail.push(event.parameters["endTime"]);
63      detail.push(event.parameters["totalTime"]);
64      detail.push(event.parameters["totalEvents"]);
65      this.pref.put(event.parameters[consts.DATA_BASE_KEY_START_TIME], detail).then(() => {
66        this.pref.flush()
67      })
68    });
69  }
70
71  private callbackFunc = (error, event) => {
72    this.pref.has(consts.DATA_BASE_KEY_TOTAL_TIMES, (err, ret) => {
73      if (ret) {
74        this.pref.get(consts.DATA_BASE_KEY_TOTAL_TIMES, []).then((value) => {
75          this.insertRecord(event, value);
76        });
77      } else {
78        let value: Array<string> = [];
79        this.insertRecord(event, value);
80      }
81      if (this.currentRecordTimes >= consts.MAX_RECORD_NUM) {
82        this.subscriber.finishCommonEvent();
83        return;
84      }
85      this.subscriber.abortCommonEvent();
86      this.subscriber.finishCommonEvent();
87      this.currentRecordTimes++;
88    })
89  }
90
91  private callbackLowFunc = (error, event) => {
92    this.currentRecordTimes = 1;
93    this.pref.get(consts.DATA_BASE_KEY_TOTAL_TIMES, []).then((value: Array<string>) => {
94      for (let i = 0; i < consts.MAX_RECORD_NUM; i++) {
95        this.pref.delete(value[i]).then(() => {
96          this.pref.flush();
97          this.subscriberLow.finishCommonEvent();
98        })
99      }
100      let records = value.slice(consts.MAX_RECORD_NUM, consts.MAX_RECORD_NUM + 1);
101      this.pref.put(consts.DATA_BASE_KEY_TOTAL_TIMES, records);
102      this.pref.flush();
103    })
104  }
105
106  jumpToStart = () => {
107    // subscribe
108    if (this.subscriber == null) {
109      let highSubscriberInfo = {
110        events: [
111          consts.COMMON_EVENT_FINISH_MEDITATION // unordered self defined event
112        ],
113        priority: 2 // 2 indicates high priority subscriber
114      };
115      commonEvent.createSubscriber(highSubscriberInfo, (err, subscriber) => {
116        this.subscriber = subscriber
117        if (subscriber != null) {
118          commonEvent.subscribe(subscriber, this.callbackFunc)
119        }
120      });
121    }
122    // subscribe
123    if (this.subscriberLow == null) {
124      let lowSubscriberInfo = {
125        events: [
126          consts.COMMON_EVENT_FINISH_MEDITATION // unordered self defined event
127        ],
128        priority: 1 // 1 indicates low priority subscriber
129      };
130      commonEvent.createSubscriber(lowSubscriberInfo, (updaerr, subscriber) => {
131        this.subscriberLow = subscriber
132        if (subscriber != null) {
133          commonEvent.subscribe(subscriber, this.callbackLowFunc)
134        }
135      });
136    }
137    let want = {
138      bundleName: 'com.samples.customcommonevent',
139      abilityName: 'MainAbility',
140    };
141    this.innerContext.startAbility(want);
142  }
143
144  jumpToHistory = () => {
145    Logger.info("ready to jump to history page");
146    router.pushUrl({
147      url: 'pages/History',
148      params: {}
149    });
150  }
151
152  jumpToSetting = () => {
153    Logger.info("ready to jump to setting page");
154    router.pushUrl({
155      url: 'pages/Setting',
156      params: {}
157    });
158  }
159
160  jumpToAbout = () => {
161    Logger.info("ready to jump to about page");
162    router.pushUrl({
163      url: 'pages/About',
164      params: {}
165    });
166  }
167
168  jumpToCommonEvent = (): void => {
169    Logger.info('ready to jump to commonEvent page');
170    let context: common.UIAbilityContext | undefined = AppStorage.get('context');
171    let want: Want = {
172      bundleName: "com.samples.cardevent",
173      abilityName: "EntryAbility",
174    };
175    context && context.startAbility(want,  (err) => {
176      if (err.code) {
177        Logger.error('StartAbility', `Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
178      }
179    });
180  };
181}