From 818f173676c0ed7c31437d9d7a88c8c2a7315c70 Mon Sep 17 00:00:00 2001 From: jiangbinghan Date: Thu, 20 Apr 2023 11:10:52 +0800 Subject: [PATCH] contact update Signed-off-by: jiangbinghan --- AppScope/app.json5 | 4 +- README_zh.md | 1 + build-profile.json5 | 2 +- common/src/main/ets/Constants.ets | 11 + .../main/ets/Application/MyAbilityStage.ts | 19 +- entry/src/main/ets/MainAbility/MainAbility.ts | 27 +- .../contact/accountants/ItemList.ets | 2 +- .../ets/component/dialer/DialerButtonView.ets | 69 +++--- .../mutisim/MutiDialerButtonView.ets | 24 +- entry/src/main/ets/feature/AudioHepler.ets | 59 ----- .../feature/missedCall/MissedCallManager.ets | 5 +- .../main/ets/model/ContactAbilityModel.ets | 30 ++- .../main/ets/model/bean/BasicDataSource.ets | 8 +- .../model/bean/CallRecordListDataSource.ts | 46 +++- .../ets/model/bean/ContactListDataSource.ts | 44 +++- .../main/ets/pages/contacts/ContactList.ets | 27 +- .../contacts/accountants/Accountants.ets | 4 +- .../ets/pages/dialer/callRecord/AllRecord.ets | 59 ++--- .../pages/dialer/callRecord/CallRecord.ets | 4 + entry/src/main/ets/pages/index.ets | 28 ++- .../main/ets/pages/phone/dialer/Dialer.ets | 17 +- .../src/main/ets/presenter/IndexPresenter.ets | 16 +- .../main/ets/presenter/PresenterManager.ets | 54 ++++ .../contact/ContactListPresenter.ets | 190 ++++++++++++-- .../accountants/AccountantsPresenter.ets | 163 ++++++------ .../dialer/callRecord/CallRecordPresenter.ets | 234 ++++++++++++++++-- entry/src/main/ets/service/CallsService.ets | 14 -- .../src/main/ets/service/ContactsService.ets | 14 -- entry/src/main/ets/util/CalendarUtil.ets | 3 +- entry/src/main/ets/workers/AudioWorker.js | 61 ----- entry/src/main/ets/workers/DataWorkerTask.ets | 121 +++++++++ entry/src/main/ets/workers/WorkFactory.ets | 9 +- entry/src/main/ets/workers/base/Worker.ts | 4 +- entry/src/main/ets/workers/base/WorkerTask.ts | 9 +- .../main/ets/workers/base/WorkerWrapper.ts | 176 ++++++------- entry/src/main/module.json5 | 2 +- .../src/main/resources/base/element/bool.json | 12 + .../base/media/dial_single_button_hd.svg | 7 + .../base/media/ic_contact_call_1_hd_dial.svg | 8 + .../base/media/ic_contact_call_2_hd_dial.svg | 8 + entry/src/main/resources/base/media/white.PNG | Bin 0 -> 123 bytes .../ets/missedcall/MissedCallNotifier.ets | 40 ++- .../main/ets/missedcall/MissedCallService.ets | 11 +- .../phonenumber/src/main/ets/PhoneNumber.ets | 4 +- .../src/main/ets/SharedPreferencesUtils.ets | 60 ----- feature/phonenumber/src/main/ets/SimUtil.ets | 196 --------------- 46 files changed, 1099 insertions(+), 807 deletions(-) delete mode 100644 entry/src/main/ets/feature/AudioHepler.ets create mode 100644 entry/src/main/ets/presenter/PresenterManager.ets delete mode 100644 entry/src/main/ets/workers/AudioWorker.js create mode 100644 entry/src/main/ets/workers/DataWorkerTask.ets create mode 100644 entry/src/main/resources/base/element/bool.json create mode 100644 entry/src/main/resources/base/media/dial_single_button_hd.svg create mode 100644 entry/src/main/resources/base/media/ic_contact_call_1_hd_dial.svg create mode 100644 entry/src/main/resources/base/media/ic_contact_call_2_hd_dial.svg create mode 100644 entry/src/main/resources/base/media/white.PNG delete mode 100644 feature/phonenumber/src/main/ets/SharedPreferencesUtils.ets delete mode 100644 feature/phonenumber/src/main/ets/SimUtil.ets diff --git a/AppScope/app.json5 b/AppScope/app.json5 index 1091cd5..e480464 100644 --- a/AppScope/app.json5 +++ b/AppScope/app.json5 @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.contacts", "vendor": "example", - "versionCode": 1000000, - "versionName": "1.0.4.012", + "versionCode": 10000003, + "versionName": "1.0.4.022", "icon": "$media:app_icon", "label": "$string:app_name", "distributedNotificationEnabled": true diff --git a/README_zh.md b/README_zh.md index d02c39b..54d8951 100644 --- a/README_zh.md +++ b/README_zh.md @@ -46,6 +46,7 @@ Contacts应用是OpenHarmony中预置的系统应用,主要的功能包含拨 │ └── app.ets # 应用生命周期/公共方法存放 │ ├── resources # 资源配置文件存放目录 │ └── config.json # 全局配置文件 +├── infra # 构建脚本 ├── signs # 签名 └── LICENSE ~~~ diff --git a/build-profile.json5 b/build-profile.json5 index 68327af..39286d4 100644 --- a/build-profile.json5 +++ b/build-profile.json5 @@ -15,7 +15,7 @@ } ], "compileSdkVersion": 10, - "compatibleSdkVersion": 9, + "compatibleSdkVersion": 10, "products": [ { "name": "default", diff --git a/common/src/main/ets/Constants.ets b/common/src/main/ets/Constants.ets index a3e22b3..5e6e72f 100644 --- a/common/src/main/ets/Constants.ets +++ b/common/src/main/ets/Constants.ets @@ -28,5 +28,16 @@ export default { SPN_INFO_CHANGED: 3, VOLTE_CHANGE: 4, CALLS_MERGE: 5 + }, + + CONFIG: { + useDataWorker: false, + needCache: false + }, + + initConfig(context: Context) { + this.CONFIG.useDataWorker = context.resourceManager.getBoolean($r('app.boolean.use_data_worker')); + this.CONFIG.needCache = context.resourceManager.getBoolean($r('app.boolean.cache_page_one')); + return this.CONFIG } } \ No newline at end of file diff --git a/entry/src/main/ets/Application/MyAbilityStage.ts b/entry/src/main/ets/Application/MyAbilityStage.ts index 48b653e..60b7ea5 100644 --- a/entry/src/main/ets/Application/MyAbilityStage.ts +++ b/entry/src/main/ets/Application/MyAbilityStage.ts @@ -1,8 +1,24 @@ +/** + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import { HiLog } from '../../../../../common/src/main/ets/util/HiLog'; +import Constants from '../../../../../common/src/main/ets/Constants'; import AbilityStage from "@ohos.app.ability.AbilityStage" import notification from '@ohos.notificationManager'; -const TAG = 'ContactListItemView '; +const TAG = 'MyAbilityStage '; export default class MyAbilityStage extends AbilityStage { onCreate() { @@ -20,5 +36,6 @@ export default class MyAbilityStage extends AbilityStage { desc: "missedCall", lockscreenVisibility: 2 }) + globalThis.config = Constants.initConfig(this.context); } } \ No newline at end of file diff --git a/entry/src/main/ets/MainAbility/MainAbility.ts b/entry/src/main/ets/MainAbility/MainAbility.ts index 6ef8ac2..c9e4433 100644 --- a/entry/src/main/ets/MainAbility/MainAbility.ts +++ b/entry/src/main/ets/MainAbility/MainAbility.ts @@ -1,3 +1,18 @@ +/** + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + import Ability from '@ohos.app.ability.UIAbility' import Window from '@ohos.window' import WorkFactory, { WorkerType } from "../workers/WorkFactory"; @@ -5,8 +20,7 @@ import { HiLog } from '../../../../../common/src/main/ets/util/HiLog'; import Want from '@ohos.app.ability.Want'; import SimManager from '../feature/sim/SimManager'; import { missedCallManager } from '../feature/missedCall/MissedCallManager'; -import CallsService from "../service/CallsService"; -import ContactsService from "../service/ContactsService"; +import PresenterManager from '../presenter/PresenterManager'; const TAG = 'MainAbility '; @@ -14,8 +28,6 @@ export default class MainAbility extends Ability { storage: LocalStorage; simManager: SimManager; mDataWorker = WorkFactory.getWorker(WorkerType.DataWorker); - mCallsService: CallsService; - mContactsService: ContactsService; updateBreakpoint(windowWidth: number) { let windowWidthVp: number = px2vp(windowWidth); @@ -51,8 +63,8 @@ export default class MainAbility extends Ability { this.onRequest(want, true); this.simManager = new SimManager(); globalThis.DataWorker = this.mDataWorker; - this.mCallsService = new CallsService(this.context, this.mDataWorker); - this.mContactsService = new ContactsService(this.context, this.mDataWorker); + globalThis.presenterManager = new PresenterManager(this.context, this.mDataWorker); + globalThis.presenterManager.onCreate(); } onNewWant(want, launchParam) { @@ -64,9 +76,8 @@ export default class MainAbility extends Ability { onDestroy() { HiLog.i(TAG, 'Ability onDestroy'); + globalThis.presenterManager.onDestroy(); this.mDataWorker.close(); - this.mCallsService.onDestroy(); - this.mContactsService.onDestroy(); } onWindowStageCreate(windowStage: Window.WindowStage) { diff --git a/entry/src/main/ets/component/contact/accountants/ItemList.ets b/entry/src/main/ets/component/contact/accountants/ItemList.ets index 43dbbdf..e9d341c 100644 --- a/entry/src/main/ets/component/contact/accountants/ItemList.ets +++ b/entry/src/main/ets/component/contact/accountants/ItemList.ets @@ -19,7 +19,7 @@ import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog'; export struct ItemList { @Link @Watch('refresh') mPresent: AccountantsPresenter; @State mTextInputValue: string = ''; - private index: number; + private index: number = 0; private typeName: string; private placeholder: Resource; @LocalStorageProp('breakpoint') curBp: string = 'sm'; diff --git a/entry/src/main/ets/component/dialer/DialerButtonView.ets b/entry/src/main/ets/component/dialer/DialerButtonView.ets index c9ad8eb..cecb534 100644 --- a/entry/src/main/ets/component/dialer/DialerButtonView.ets +++ b/entry/src/main/ets/component/dialer/DialerButtonView.ets @@ -56,42 +56,41 @@ export struct DialerButtonView { build() { Row() { - Button() { - Image($r('app.media.dial_single_button_volte')) - .width($r("app.float.id_item_height_large")) - .height($r("app.float.id_item_height_large")) + if (!this.haveMultiSimCard) { + if (this.haveSimCard && this.haveVoLteReg) { + Button() { + Image($r('app.media.dial_single_button_hd')) + .width($r("app.float.id_item_height_large")) + .height($r("app.float.id_item_height_large")) + } + .width(this.mPresenter.dialerButtonHeight) + .height(this.mPresenter.dialerButtonHeight) + .backgroundColor($r('sys.color.ohos_id_color_connected')) + .opacity(!EnvironmentProp.isTablet() || this.mPresenter.btnShow || this.haveSimCard + ? 1 : $r('sys.float.ohos_id_alpha_disabled')) + .onClick(() => { + this.dialClick(); + }) + } else { + Button() { + Image($r("app.media.ic_public_phone_filled_white")) + .width($r("app.float.id_card_margin_xxxxl")) + .height($r("app.float.id_card_margin_xxxxl")) + } + .width(this.mPresenter.dialerButtonHeight) + .height(this.mPresenter.dialerButtonHeight) + .backgroundColor($r('sys.color.ohos_id_color_connected')) + .opacity(!EnvironmentProp.isTablet() || this.mPresenter.btnShow || this.haveSimCard + ? 1 : $r('sys.float.ohos_id_alpha_disabled')) + .onClick(() => { + this.dialClick(); + }) + } + } else { + MutiDialerButtonView({ + mPresenter: $mPresenter, + }).height(this.mPresenter.dialerButtonHeight) } - .width(this.mPresenter.dialerButtonHeight) - .height(this.mPresenter.dialerButtonHeight) - .visibility(this.haveMultiSimCard ? Visibility.None : (this.haveSimCard && this.haveVoLteReg ? - Visibility.Visible : Visibility.None)) - .backgroundColor($r('sys.color.ohos_id_color_connected')) - .opacity(!EnvironmentProp.isTablet() || this.mPresenter.btnShow || this.haveSimCard - ? 1 : $r('sys.float.ohos_id_alpha_disabled')) - .onClick(() => { - this.dialClick(); - }) - - Button() { - Image($r("app.media.ic_public_phone_filled_white")) - .width($r("app.float.id_card_margin_xxxxl")) - .height($r("app.float.id_card_margin_xxxxl")) - } - .width(this.mPresenter.dialerButtonHeight) - .height(this.mPresenter.dialerButtonHeight) - .visibility(this.haveMultiSimCard ? Visibility.None : (this.haveSimCard && this.haveVoLteReg ? - Visibility.None : Visibility.Visible)) - .backgroundColor($r('sys.color.ohos_id_color_connected')) - .opacity(!EnvironmentProp.isTablet() || this.mPresenter.btnShow || this.haveSimCard - ? 1 : $r('sys.float.ohos_id_alpha_disabled')) - .onClick(() => { - this.dialClick(); - }) - - MutiDialerButtonView({ - mPresenter: $mPresenter, - }).height(this.mPresenter.dialerButtonHeight) - .visibility(this.haveMultiSimCard ? Visibility.Visible : Visibility.None) }.width(this.mPresenter.dialerButtonWidth) .height(this.mPresenter.dialerButtonHeight) .justifyContent(FlexAlign.Center) diff --git a/entry/src/main/ets/component/mutisim/MutiDialerButtonView.ets b/entry/src/main/ets/component/mutisim/MutiDialerButtonView.ets index ddb9e96..ecbe1bc 100644 --- a/entry/src/main/ets/component/mutisim/MutiDialerButtonView.ets +++ b/entry/src/main/ets/component/mutisim/MutiDialerButtonView.ets @@ -25,6 +25,7 @@ export struct MutiDialerButtonView { @StorageLink("spnList") simNames: Array = ["", ""]; @StorageLink("voLteRegStates") voLteRegStates: boolean[] = [false, false]; private dailImg = [$r("app.media.ic_public_phone1_filled"), $r("app.media.ic_public_phone2_filled")] + private dailHDImg = [$r("app.media.ic_contact_call_1_hd_dial"), $r("app.media.ic_contact_call_2_hd_dial")] dialClick(slot: number) { this.mPresenter.callBtnClick = true; @@ -43,23 +44,12 @@ export struct MutiDialerButtonView { ForEach(this.simNames, (item, index) => { //DailButton for voLte Row() { - Column() { - Image(this.dailImg[index]) - .width(this.voLteRegStates[index] ? "14vp" : "18vp") - .height(this.voLteRegStates[index] ? "14vp" : "18vp") - .onError((event => { - HiLog.e(TAG, "Sim:" + index + " Image onError" + JSON.stringify(event)) - })) - Image($r('app.media.ic_dail_button_volte')) - .onError((event => { - HiLog.e(TAG, "ic_dail_button_volte Image onError" + JSON.stringify(event)) - })) - .height('10vp') - .width('16vp') - .visibility(this.voLteRegStates[index] ? Visibility.Visible : Visibility.None) - }.width("18vp") - .justifyContent(FlexAlign.Center) - .alignItems(HorizontalAlign.Center) + Image(this.voLteRegStates[index] ? this.dailHDImg[index] : this.dailImg[index]) + .width("18vp") + .height("18vp") + .onError((event => { + HiLog.e(TAG, "Sim:" + index + " Image onError" + JSON.stringify(event)) + })) Text(this.simNames[index]) .fontColor($r("sys.color.ohos_id_color_primary_contrary")) diff --git a/entry/src/main/ets/feature/AudioHepler.ets b/entry/src/main/ets/feature/AudioHepler.ets deleted file mode 100644 index 681c361..0000000 --- a/entry/src/main/ets/feature/AudioHepler.ets +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import worker from '@ohos.worker'; -import { HiLog } from '../../../../../common/src/main/ets/util/HiLog'; - -const TAG = "AudioWorker "; - -export class AudioHepler { - private workerName: string; - private workerUri: string; - private mWorker; - constructor(name: string, workerUri: string) { - this.workerName = name; - this.workerUri = workerUri; - this.initWorker(); - } - - private initWorker(): void { - this.mWorker = new worker.Worker(this.workerUri, { type: "classic", name: this.workerName }); - this.mWorker.onerror = this.onError.bind(this); - this.mWorker.onmessageError = this.onMessageError.bind(this); - this.mWorker.onexit = this.onExit.bind(this); - this.mWorker.onmessage = this.onMessage.bind(this); - } - - public onError(e: any): void { - HiLog.e(TAG, "AudioWorker is error" + JSON.stringify(e)); - } - - public onMessageError(e: any): void { - HiLog.e(TAG, "AudioWorker Message is error" + JSON.stringify(e)); - } - - public onExit(e: any): void { - HiLog.e(TAG, "AudioWorker is Exit"); - } - - public onMessage(e: any): void { - HiLog.e(TAG, "AudioWorker return message"); - } - - public postMessage(message: any): void { - HiLog.i(TAG, "AudioWorker postMessage"); - this.mWorker.postMessage(message); - } -} \ No newline at end of file diff --git a/entry/src/main/ets/feature/missedCall/MissedCallManager.ets b/entry/src/main/ets/feature/missedCall/MissedCallManager.ets index d9bb7cf..8603005 100644 --- a/entry/src/main/ets/feature/missedCall/MissedCallManager.ets +++ b/entry/src/main/ets/feature/missedCall/MissedCallManager.ets @@ -1,5 +1,5 @@ /** - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import { HiLog } from '../../../../../../common'; import commonEvent from '@ohos.commonEventManager'; import { PhoneNumber } from '../../../../../../feature/phonenumber'; @@ -35,7 +36,7 @@ class MissedCallManager { } private async autoCall(phoneNumber: string) { - HiLog.i(TAG, 'autoCall:' + phoneNumber) + HiLog.i(TAG, 'autoCall:') let readySimCount: number = 0; let readySim = -1; for (let i = 0; i < telephonySim.getMaxSimCount(); i++) { diff --git a/entry/src/main/ets/model/ContactAbilityModel.ets b/entry/src/main/ets/model/ContactAbilityModel.ets index 0c5bfff..6c3d1e2 100644 --- a/entry/src/main/ets/model/ContactAbilityModel.ets +++ b/entry/src/main/ets/model/ContactAbilityModel.ets @@ -818,20 +818,24 @@ export default { */ updateContact: async function (DAHelper, addParams, callBack, context?) { HiLog.i(TAG, 'Start to update contacts.'); - if (DAHelper == undefined || DAHelper.length == 0 || DAHelper == null) { - DAHelper = await dataShare.createDataShareHelper(context ? context : globalThis.context, Contacts.CONTENT_URI); + try { + if (DAHelper == undefined || DAHelper.length == 0 || DAHelper == null) { + DAHelper = await dataShare.createDataShareHelper(context ? context : globalThis.context, Contacts.CONTENT_URI); + } + let condition = new dataSharePredicates.DataSharePredicates(); + condition.equalTo('raw_contact_id', addParams.id); + DAHelper.delete( + Data.CONTENT_URI, + condition, + ).then(data => { + this.dealParam(DAHelper, addParams, false, callBack); + }).catch(error => { + HiLog.e(TAG, 'updateContact-update contact error: %s', JSON.stringify(error.message)); + }); + HiLog.i(TAG, 'End to update contacts.'); + } catch(err) { + HiLog.e(TAG, 'updateContact err : ' + JSON.stringify(err)); } - let condition = new dataSharePredicates.DataSharePredicates(); - condition.equalTo('raw_contact_id', addParams.id); - DAHelper.delete( - Data.CONTENT_URI, - condition, - ).then(data => { - this.dealParam(DAHelper, addParams, false, callBack); - }).catch(error => { - HiLog.e(TAG, 'updateContact-update contact error: %s', JSON.stringify(error.message)); - }); - HiLog.i(TAG, 'End to update contacts.'); }, /** * Querying IDs by Phone Number diff --git a/entry/src/main/ets/model/bean/BasicDataSource.ets b/entry/src/main/ets/model/bean/BasicDataSource.ets index d410bdf..902abf5 100644 --- a/entry/src/main/ets/model/bean/BasicDataSource.ets +++ b/entry/src/main/ets/model/bean/BasicDataSource.ets @@ -51,25 +51,25 @@ export class BasicDataSource implements IDataSource { notifyDataAdd(index: number): void { this.listeners.forEach(listener => { - listener.onDataAdded(index); + listener.onDataAdd(index); }) } notifyDataChange(index: number): void { this.listeners.forEach(listener => { - listener.onDataChanged(index) + listener.onDataChange(index) }) } notifyDataDelete(index: number): void { this.listeners.forEach(listener => { - listener.onDataDeleted(index); + listener.onDataDelete(index); }) } notifyDataMove(from: number, to: number): void { this.listeners.forEach(listener => { - listener.onDataMoved(from, to); + listener.onDataMove(from, to); }) } } diff --git a/entry/src/main/ets/model/bean/CallRecordListDataSource.ts b/entry/src/main/ets/model/bean/CallRecordListDataSource.ts index 815d74e..45b8fd4 100644 --- a/entry/src/main/ets/model/bean/CallRecordListDataSource.ts +++ b/entry/src/main/ets/model/bean/CallRecordListDataSource.ts @@ -19,7 +19,9 @@ import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil' const TAG = "CallRecordListDataSource"; export default class CallRecordListDataSource extends BasicDataSource { - private callLogData: [] = []; + private callLogData: any[] = []; + private isShow: boolean; + private isDataReload: boolean; public totalCount(): number { return this.callLogData.length; @@ -34,9 +36,45 @@ export default class CallRecordListDataSource extends BasicDataSource { } } - public refresh(callLogData) { - HiLog.i(TAG, ' refresh!'); + public refreshAll(callLogData) { + HiLog.i(TAG, ' refreshAll!'); this.callLogData = callLogData; - this.notifyDataReload(); + this.setDataReload(true); + } + + public setIsShow(isShow: boolean) { + if (this.isShow == isShow) { + return; + } + this.isShow = isShow; + HiLog.i(TAG, ' setIsShow:' + this.isShow); + this.setDataReload(this.isDataReload); + } + + public refresh(start: number, count: number, callLogData: []) { + HiLog.i(TAG, ' refresh!'); + this.callLogData.splice(start, count, ...callLogData); + this.setDataReload(true); + } + + public remove(index: number, count?) { + if (index < 0 || index >= this.totalCount()) { + return; + } + HiLog.i(TAG, ' remove:' + index); + this.callLogData.splice(index, count ? count : 1); + this.notifyDataDelete(index); + } + + private setDataReload(isDataReload: boolean) { + if (this.isShow) { + if (isDataReload) { + HiLog.i(TAG, 'notifyDataReload'); + this.notifyDataReload(); + } + this.isDataReload = false; + } else { + this.isDataReload = isDataReload; + } } } \ No newline at end of file diff --git a/entry/src/main/ets/model/bean/ContactListDataSource.ts b/entry/src/main/ets/model/bean/ContactListDataSource.ts index f3ca4eb..b9c1878 100644 --- a/entry/src/main/ets/model/bean/ContactListDataSource.ts +++ b/entry/src/main/ets/model/bean/ContactListDataSource.ts @@ -22,7 +22,8 @@ const TAG = "ContactListDataSource"; export default class ContactListDataSource extends BasicDataSource { private contactList: ContactVo[] = []; - private contactsCount: number = 0; + private isShow: boolean; + private isDataReload: boolean; public totalCount(): number { return this.contactList.length; @@ -56,9 +57,46 @@ export default class ContactListDataSource extends BasicDataSource { } } - public refresh(contactList: ContactVo[]) { - HiLog.i(TAG, ' refresh!'); + public refreshAll(contactList: ContactVo[]) { + HiLog.i(TAG, ' refreshAll!'); this.contactList = contactList; + this.setDataReload(true); + } + + public setIsShow(isShow: boolean) { + if (this.isShow == isShow) { + return; + } + HiLog.i(TAG, ' setIsShow:' + isShow); + this.isShow = isShow; + this.setDataReload(this.isDataReload) + } + + public refresh(start: number, count: number, contactList: ContactVo[]) { + HiLog.i(TAG, ' refresh!'); + this.contactList.splice(start, count, ...contactList); this.notifyDataReload(); + this.setDataReload(true); + } + + public remove(index: number, count?) { + if (index < 0 || index >= this.totalCount()) { + return; + } + HiLog.i(TAG, ' remove:' + index); + this.contactList.splice(index, count ? count : 1); + this.notifyDataDelete(index); + } + + private setDataReload(isDataReload: boolean) { + if (this.isShow) { + if (isDataReload) { + HiLog.i(TAG, 'notifyDataReload'); + this.notifyDataReload(); + } + this.isDataReload = false; + } else { + this.isDataReload = isDataReload; + } } } \ No newline at end of file diff --git a/entry/src/main/ets/pages/contacts/ContactList.ets b/entry/src/main/ets/pages/contacts/ContactList.ets index 2fb4362..0ae2708 100644 --- a/entry/src/main/ets/pages/contacts/ContactList.ets +++ b/entry/src/main/ets/pages/contacts/ContactList.ets @@ -35,22 +35,18 @@ export default struct ContactListPage { emitterId: number = 2; refresh() { - if (AppStorage.Has('contactList')) { - let contactList: any = AppStorage.Get('contactList'); - this.contactListListLen = contactList.length; - this.mContactPresenter.refresh(contactList); + let contactListLen = this.mContactPresenter.contactListDataSource.totalCount(); + if (this.contactListListLen != contactListLen) { + this.contactListListLen = contactListLen; + this.mContactPresenter = globalThis.presenterManager.contactListPresenter; } } aboutToAppear() { HiLog.i(TAG, 'Contact aboutToAppear!'); this.mContactPresenter.aboutToAppear(); - let innerEvent = { - eventId: Constants.Event.CONTACTS_CHANGE, - priority: emitter.EventPriority.HIGH - }; - emitter.on(innerEvent, () => { - this.refresh(); + this.mContactPresenter.bindUI(() => { + this.refresh() }) this.refresh(); } @@ -61,14 +57,6 @@ export default struct ContactListPage { emitter.off(Constants.Event.CONTACTS_CHANGE); } - onPageShow() { - this.mContactPresenter.onPageShow(); - } - - onPageHide() { - this.mContactPresenter.onPageHide(); - } - build() { Column() { if (this.contactListListLen == 0) { @@ -220,7 +208,8 @@ struct ContactContent { .width('100%') .height('100%') .listDirection(Axis.Vertical) - .edgeEffect(EdgeEffect.Spring) + .edgeEffect(EdgeEffect.None) + .scrollBar(BarState.Off) } } .height('100%') diff --git a/entry/src/main/ets/pages/contacts/accountants/Accountants.ets b/entry/src/main/ets/pages/contacts/accountants/Accountants.ets index 932a61d..a398f2e 100644 --- a/entry/src/main/ets/pages/contacts/accountants/Accountants.ets +++ b/entry/src/main/ets/pages/contacts/accountants/Accountants.ets @@ -332,7 +332,7 @@ struct Accountants { , (item) => { ItemList({ mPresent: $mPresenter, - index: item.i, + index: item?.i, typeName: "phone", placeholder: $r("app.string.phone_number") }) @@ -357,7 +357,7 @@ struct Accountants { , (item) => { ItemList({ mPresent: $mPresenter, - index: item.i, + index: item?.i, typeName: "email", placeholder: $r("app.string.email") }) diff --git a/entry/src/main/ets/pages/dialer/callRecord/AllRecord.ets b/entry/src/main/ets/pages/dialer/callRecord/AllRecord.ets index 43b9ca9..6ee9374 100644 --- a/entry/src/main/ets/pages/dialer/callRecord/AllRecord.ets +++ b/entry/src/main/ets/pages/dialer/callRecord/AllRecord.ets @@ -23,58 +23,36 @@ import DialerPresenter from '../../../presenter/dialer/DialerPresenter'; import DetailPresenter from '../../../presenter/contact/detail/DetailPresenter'; import { PhoneNumber } from '../../../../../../../feature/phonenumber/src/main/ets/PhoneNumber'; import IndexPresenter from '../../../presenter/IndexPresenter'; -import { HiLog, ArrayUtil } from "../../../../../../../common" -import Constants from '../../../../../../../common/src/main/ets/Constants'; -import emitter from '@ohos.events.emitter' +import { HiLog } from "../../../../../../../common" const TAG = "AllRecord "; @Component export default struct AllRecord { - @Link mPresenter: CallRecordPresenter; + @Link @Watch("onChanged") mPresenter: CallRecordPresenter; /*0all 1miss*/ recordType: number = 0; - emitterId: number = 1; @State callLogListEmpty: boolean = true; @State missedListEmpty: boolean = true; - refresh() { - if (this.recordType === 0) { - if (AppStorage.Has('callLogList')) { - let callLogList: any = AppStorage.Get('callLogList'); - const callLogEmpty: boolean = ArrayUtil.isEmpty(callLogList) - if (this.callLogListEmpty != callLogEmpty) { - this.callLogListEmpty = callLogEmpty; - } - this.mPresenter.refreshCallLogList(callLogList); - } - } else { - if (AppStorage.Has('missedList')) { - let missedList: any = AppStorage.Get('missedList') - const missedEmpty: boolean = ArrayUtil.isEmpty(missedList) - if (this.missedListEmpty != missedEmpty) { - this.missedListEmpty = missedEmpty; - } - this.mPresenter.refreshMissedList(missedList) - } + onChanged() { + let callLogIsEmpty = this.mPresenter.mAllCallRecordListDataSource.totalCount() <= 0; + if (this.callLogListEmpty != callLogIsEmpty) { + this.callLogListEmpty = callLogIsEmpty + } + let missLogIsEmpty = this.mPresenter.mMissCallRecordListDataSource.totalCount() <= 0; + if (this.missedListEmpty != missLogIsEmpty) { + this.missedListEmpty = missLogIsEmpty } } aboutToAppear() { HiLog.i(TAG, 'aboutToAppear,recordType:' + this.recordType) - let innerEvent = { - eventId: Constants.Event.CALLS_CHANGE, - priority: emitter.EventPriority.HIGH - }; - emitter.on(innerEvent, () => { - this.refresh(); - }) - this.refresh(); + this.onChanged(); } aboutToDisappear() { HiLog.i(TAG, 'aboutToDisappear,recordType:' + this.recordType) - emitter.off(Constants.Event.CALLS_CHANGE); } build() { @@ -99,7 +77,7 @@ struct RecordView { LazyForEach(this.recordType === 0 ? this.mPresenter.mAllCallRecordListDataSource : this.mPresenter.mMissCallRecordListDataSource, (item, index: number) => { ListItem() { - ContactItem({ mPresenter: $mPresenter, item: item }); + ContactItem({ mPresenter: $mPresenter, item: item, index: index }); } .height($r("app.float.id_item_height_max")) }, item => JSON.stringify(item)) @@ -114,7 +92,8 @@ struct RecordView { .margin({ bottom: this.curBp === 'lg' ? '110vp' : 0 }) .flexShrink(1) .listDirection(Axis.Vertical) - .edgeEffect(EdgeEffect.Spring) + .edgeEffect(EdgeEffect.None) + .scrollBar(BarState.Off) } } @@ -154,6 +133,7 @@ struct ContactItem { @State mIndexPresenter: IndexPresenter = IndexPresenter.getInstance(); @Link mPresenter: CallRecordPresenter @State item: { [key: string]: any } = {}; + index: number; @State isEmergencyNum: boolean = false; @LocalStorageProp('breakpoint') curBp: string = 'sm'; @StorageLink("haveMultiSimCard") haveMultiSimCard: boolean = false; @@ -165,7 +145,7 @@ struct ContactItem { this.deleteDialogController.close(); }, confirm: () => { - this.mPresenter.deleteCallLog(this.item.ids); + this.mPresenter.deleteCallLog(this.item.ids, this.index); }, title: $r("app.string.deleteCallLog_dialog_title"), cancalText: $r("app.string.cancel"), @@ -232,7 +212,8 @@ struct ContactItem { .margin({ right: $r("app.float.id_card_margin_mid"), top: "4vp", - }).visibility(this.item.isHD ? Visibility.Visible : Visibility.None); + }) + .visibility(this.item.isHD ? Visibility.Visible : Visibility.None); Text(this.item.numberLocation ? this.item.numberLocation @@ -261,6 +242,8 @@ struct ContactItem { .margin({ top: $r("app.float.id_card_margin_sm"), right: 24 }) .onClick(() => { this.mPresenter.jumpToContactDetail(this.item.phoneNumber); + DialerPresenter.getInstance().panelShow = true; + AppStorage.SetOrCreate("showDialBtn", true); }) } .height($r("app.float.id_item_height_max")) @@ -292,6 +275,8 @@ struct ContactItem { this.mPresenter.dialing(this.item.phoneNumber); } } + DialerPresenter.getInstance().panelShow = true; + AppStorage.SetOrCreate("showDialBtn", true); }) .bindContextMenu(this.MenuBuilder, ResponseType.LongPress) } diff --git a/entry/src/main/ets/pages/dialer/callRecord/CallRecord.ets b/entry/src/main/ets/pages/dialer/callRecord/CallRecord.ets index 05c5652..76c2f28 100644 --- a/entry/src/main/ets/pages/dialer/callRecord/CallRecord.ets +++ b/entry/src/main/ets/pages/dialer/callRecord/CallRecord.ets @@ -33,6 +33,9 @@ export default struct CallRecord { aboutToAppear(){ HiLog.i(TAG, 'aboutToAppear'); this.mPresenter.aboutToAppear(); + this.mPresenter.bindUI(()=>{ + this.mPresenter = CallRecordPresenter.getInstance(); + }) } aboutToDisappear() { HiLog.i(TAG, 'aboutToDisappear'); @@ -56,6 +59,7 @@ export default struct CallRecord { } .onChange((index: number) => { this.bottomTabIndex = index + this.mPresenter.setTabIndex(index); }) .vertical(false) .barHeight(0) diff --git a/entry/src/main/ets/pages/index.ets b/entry/src/main/ets/pages/index.ets index 704d06f..9908845 100644 --- a/entry/src/main/ets/pages/index.ets +++ b/entry/src/main/ets/pages/index.ets @@ -43,6 +43,13 @@ struct Index { this.controller.changeIndex(this.mIndexPresenter.tabsIndex); this.bottomTabIndex = this.mIndexPresenter.tabsIndex; this.mDialerPresenter.editPhoneNumber(this.mIndexPresenter.editPhoneNumber); + if (this.mIndexPresenter.tabsIndex == 0) { + ContactListPresenter.getInstance().setPageShow(false); + CallRecordPresenter.getInstance().setPageShow(true); + } else { + CallRecordPresenter.getInstance().setPageShow(false); + ContactListPresenter.getInstance().setPageShow(true); + } } pageTransition() { @@ -52,6 +59,18 @@ struct Index { onPageShow() { this.mIndexPresenter.onPageShow(); + if (this.bottomTabIndex == 0) { + ContactListPresenter.getInstance().setPageShow(false); + CallRecordPresenter.getInstance().setPageShow(true); + } else { + CallRecordPresenter.getInstance().setPageShow(false); + ContactListPresenter.getInstance().setPageShow(true); + } + } + + onPageHide() { + ContactListPresenter.getInstance().setPageShow(false); + CallRecordPresenter.getInstance().setPageShow(false); } aboutToAppear() { @@ -116,7 +135,6 @@ struct Index { .barHeight(0) .scrollable(false) .animationDuration(0) - } .layoutWeight(this.curBp === 'lg' ? 1 : 0) .flexShrink(this.curBp === 'lg' ? 0 : 1) @@ -179,11 +197,11 @@ struct TabBars { this.bottomTabIndex = item; this.mIndexPresenter.tabsIndex = item; if (item == 0) { - ContactListPresenter.getInstance().onPageHide(); - CallRecordPresenter.getInstance().onPageShow(); + ContactListPresenter.getInstance().setPageShow(false); + CallRecordPresenter.getInstance().setPageShow(true); } else if (item == 1) { - CallRecordPresenter.getInstance().onPageHide(); - ContactListPresenter.getInstance().onPageShow(); + CallRecordPresenter.getInstance().setPageShow(false); + ContactListPresenter.getInstance().setPageShow(true); } } }) diff --git a/entry/src/main/ets/pages/phone/dialer/Dialer.ets b/entry/src/main/ets/pages/phone/dialer/Dialer.ets index c5f1535..9658f07 100644 --- a/entry/src/main/ets/pages/phone/dialer/Dialer.ets +++ b/entry/src/main/ets/pages/phone/dialer/Dialer.ets @@ -221,16 +221,13 @@ export default struct Call { } .height('100%') .zIndex(1) - .gesture( - SwipeGesture({ fingers: 1, direction: SwipeDirection.Vertical, speed: 150 }) - .onAction((event: GestureEvent) => { - if (this.mPresenter.callBtnClick) { - return; - } - this.mPresenter.panelShow = false; - this.showDialBtn = false; - }) - ) + .onTouch(() => { + if (this.mPresenter.callBtnClick) { + return; + } + this.mPresenter.panelShow = false; + this.showDialBtn = false; + }) } .width('100%') .height('100%') diff --git a/entry/src/main/ets/presenter/IndexPresenter.ets b/entry/src/main/ets/presenter/IndexPresenter.ets index 843a0d8..5faedd4 100644 --- a/entry/src/main/ets/presenter/IndexPresenter.ets +++ b/entry/src/main/ets/presenter/IndexPresenter.ets @@ -14,16 +14,12 @@ */ import router from '@ohos.router'; -import { CallLogRepository } from '../../../../../feature/call'; -import { ContactRepository } from '../../../../../feature/contact/src/main/ets/repo/ContactRepository'; import pasteboard from '@ohos.pasteboard'; import { HiLog } from '../../../../../common/src/main/ets/util/HiLog'; import { StringUtil } from '../../../../../common/src/main/ets/util/StringUtil'; import StringFormatUtil from '../util/StringFormatUtil'; -import CallRecordPresenter from './dialer/callRecord/CallRecordPresenter'; import { missedCallManager } from '../feature/missedCall/MissedCallManager'; -import emitter from '@ohos.events.emitter'; -import Constants from '../../../../../common/src/main/ets/Constants'; +import CallRecordPresenter from './dialer/callRecord/CallRecordPresenter'; const TAG = 'IndexPresenter '; @@ -33,10 +29,6 @@ export default class IndexPresenter { isEditNum: boolean = false; editPhoneNumber: string = ""; tabsIndex: number = 0; - innerEvent = { - eventId: Constants.Event.CALLS_MERGE, - priority: emitter.EventPriority.HIGH - }; public static getInstance(): IndexPresenter { if (!IndexPresenter.instance) { @@ -59,7 +51,7 @@ export default class IndexPresenter { this.getNewWant(); if (parseInt(StringFormatUtil.judgeSysTime()) !== AppStorage.Get("sysTime")) { HiLog.i(TAG, 'DO requestItem cause systemTime changed'); - emitter.emit(this.innerEvent) + CallRecordPresenter.getInstance().requestItem(); AppStorage.SetOrCreate("sysTime", parseInt(StringFormatUtil.judgeSysTime())); } } @@ -77,10 +69,6 @@ export default class IndexPresenter { aboutToDisappear() { HiLog.i(TAG, 'aboutToDisappear !!!'); - CallLogRepository.getInstance().unRegisterDataChangeObserver(() => { - }); - ContactRepository.getInstance().unRegisterDataChangeObserver(() => { - }); } getNewWant() { diff --git a/entry/src/main/ets/presenter/PresenterManager.ets b/entry/src/main/ets/presenter/PresenterManager.ets new file mode 100644 index 0000000..9f82bee --- /dev/null +++ b/entry/src/main/ets/presenter/PresenterManager.ets @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { HiLog } from '../../../../../common/src/main/ets/util/HiLog'; +import ContactListPresenter from './contact/ContactListPresenter'; +import CallRecordPresenter from './dialer/callRecord/CallRecordPresenter'; +import WorkerWrapper from "../workers/base/WorkerWrapper"; + +const TAG = 'PageManager' + +export default class PresenterManager { + static MAIN_PAGE: string = 'pages/index' + context: Context; + worker: WorkerWrapper; + callRecordPresenter: CallRecordPresenter = CallRecordPresenter.getInstance(); + contactListPresenter: ContactListPresenter = ContactListPresenter.getInstance(); + + constructor(context: Context, worker: WorkerWrapper) { + this.context = context; + this.worker = worker; + } + + onCreate() { + HiLog.i(TAG, "onCreate") + this.callRecordPresenter.onCreate(this.context, this.worker); + this.contactListPresenter.onCreate(this.context, this.worker); + if (globalThis.config.needCache) { + this.initDataCache(); + } + } + + initDataCache() { + CallRecordPresenter.getInstance().cachePageOne(); + ContactListPresenter.getInstance().cachePageOne(); + } + + onDestroy() { + HiLog.i(TAG, "onDestroy") + this.callRecordPresenter.onDestroy(); + this.contactListPresenter.onDestroy(); + } +} \ No newline at end of file diff --git a/entry/src/main/ets/presenter/contact/ContactListPresenter.ets b/entry/src/main/ets/presenter/contact/ContactListPresenter.ets index 9ce5036..603f027 100644 --- a/entry/src/main/ets/presenter/contact/ContactListPresenter.ets +++ b/entry/src/main/ets/presenter/contact/ContactListPresenter.ets @@ -19,11 +19,11 @@ import { ContactVo } from '../../model/bean/ContactVo'; import { ArrayUtil } from '../../../../../../common/src/main/ets/util/ArrayUtil'; import { CallLogRepository } from '../../../../../../feature/call/src/main/ets/repo/CallLogRepository'; import { ContactRepository } from '../../../../../../feature/contact/src/main/ets/repo/ContactRepository'; -import emitter from '@ohos.events.emitter'; import ContactListDataSource from '../../model/bean/ContactListDataSource'; +import WorkerWrapper from '../../workers/base/WorkerWrapper'; const TAG = 'ContactListPresenter '; - +const DELAY_TIME: number = 1000; /** * Type of the control that is clicked in the contact list. */ @@ -40,19 +40,35 @@ export enum ContactClickType { export default class ContactListPresenter { private static sInstance: ContactListPresenter; indexs: string[] = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '…']; + contactListPages: Array = []; curItem: ContactVo = new ContactVo("", "", "", "", "", "", true, "", ""); - total: number = 0; + page: number = 0; + limit: number = 0; + refreshIndex: number = 0; queryContactsType: string = 'all'; isEmptyGroup: boolean = true; shareList: Resource[] = [$r("app.string.qr_code"), $r("app.string.v_card"), $r("app.string.text")]; settingsMenu: Resource[] = [$r("app.string.contact_setting_type_scancard"), $r("app.string.call_setting_type_setting")]; contactListDataSource: ContactListDataSource = new ContactListDataSource(); isShow: boolean = false; + context: Context; + worker: WorkerWrapper; + loading: boolean; + initStarted: boolean = false; + taskId: number = undefined; + refreshState: () => void + onContactChange = () => { + HiLog.i(TAG, 'onContactChange refresh'); + this.setDelayTask(); + } private constructor() { } public static getInstance(): ContactListPresenter { + if (globalThis.presenterManager?.contactListPresenter) { + return globalThis.presenterManager.contactListPresenter; + } if (ContactListPresenter.sInstance == null) { HiLog.i(TAG, 'Contact getInstance!'); ContactListPresenter.sInstance = new ContactListPresenter(); @@ -60,29 +76,164 @@ export default class ContactListPresenter { return ContactListPresenter.sInstance; } + onCreate(context: Context, worker: WorkerWrapper) { + this.context = context; + this.worker = worker; + ContactRepository.getInstance().registerDataChangeObserver(this.onContactChange); + } + + onDestroy() { + ContactRepository.getInstance().unRegisterDataChangeObserver(this.onContactChange); + } + + bindUI(refreshState?: () => void) { + this.refreshState = refreshState; + } + + startInit() { + if (this.initStarted) { + return; + } + HiLog.i(TAG, "startInit"); + this.initStarted = true; + if (this.page == 0) { + this.page++; + } + this.refreshContinue(); + } + + cachePageOne() { + if (!this.initStarted && !this.loading) { + HiLog.i(TAG, "cachePageOne") + this.page = 1; + this.refreshIndex = 0; + this.refreshContinue(); + } else { + HiLog.i(TAG, "no need cachePageOne"); + } + } + aboutToAppear() { - this.isShow = true; + HiLog.i(TAG, 'Contact aboutToAppear!'); + this.startInit(); } aboutToDisappear() { - this.isShow = false; + HiLog.i(TAG, 'Contact aboutToDisappear!'); } - onPageShow() { - HiLog.i(TAG, 'Contact onPageShow!'); - this.isShow = true; + setPageShow(isShow: boolean) { + if (this.isShow == isShow) { + return; + } + this.isShow = isShow; + if (this.isShow) { + this.startInit(); + } + this.contactListDataSource.setIsShow(isShow); } - onPageHide() { - HiLog.i(TAG, 'Contact onPageHide!'); - this.isShow = false; + requestItem() { + HiLog.i(TAG, 'Contacts requestItem!'); + if (this.page == 0) { + this.page++; + this.refreshContinue(); + } else if (!this.initStarted && !this.loading) { + this.cachePageOne(); + } else { + HiLog.i(TAG, 'isLoading'); + } } - - refresh(contactList) { - this.contactListDataSource.refresh(contactList); + setDelayTask() { + if (this.taskId != undefined) { + clearTimeout(this.taskId); + this.taskId = undefined; + } + let delay: number = 0; + if (this.page != 0) { + delay += DELAY_TIME; + } + if (!this.isShow) { + delay += DELAY_TIME; + } + if (delay > 0) { + this.taskId = setTimeout(() => { + if (this.page != 0) { + this.setDelayTask(); + } else { + this.requestItem(); + } + }, delay); + } else { + this.requestItem(); + } } + refreshContinue() { + if (this.loading) { + HiLog.i(TAG, 'refreshContinue is loading'); + return; + } + if (this.page == 0) { + HiLog.i(TAG, 'refreshContinue end'); + return; + } + if (this.page == 1) { + this.limit = 50; + } else { + this.limit = 500; + } + this.refreshPage(this.page, this.limit, () => { + if (this.initStarted) { + setTimeout(() => { + this.refreshContinue(); + },!this.isShow ? 700 : 1); + } + }) + } + + refreshPage(page: number, limit: number, callback?: () => void) { + this.loading = true; + let actionData: any = {}; + actionData.page = page; + actionData.limit = limit; + this.worker.sendRequest("getAllContact", { + actionData: actionData, + context: this.context + }, (result) => { + HiLog.i(TAG, `refreshPage ${page} getAllContact, length is: ` + result.length); + if (Array.prototype.isPrototypeOf(result)) { + this.contactListDataSource.refresh(this.refreshIndex, this.contactListPages[page -1], result); + } + this.contactListPages[page -1] = result.length; + this.refreshIndex += this.contactListPages[page -1]; + if (this.refreshState) { + this.refreshState(); + } + let contactCount = result.length; + if (contactCount < limit) { + this.page = 0; + HiLog.i(TAG, 'Contacts load completed: ' + JSON.stringify(this.contactListDataSource.totalCount())); + if (this.contactListPages.length > page) { + this.contactListPages.splice(page, this.contactListPages.length - page); + } + if (this.contactListDataSource.totalCount() > this.refreshIndex) { + this.contactListDataSource.remove(this.refreshIndex, this.contactListDataSource.totalCount() - this.refreshIndex); + } + this.refreshIndex = 0; + this.loading = false; + } else { + this.page = page + 1; + this.loading = false; + if (callback) { + callback(); + } + } + }) + } + + /** * Touch and hold the current contact information saved by a contact item in the contact list. * The information can be deleted or shared later. @@ -108,11 +259,16 @@ export default class ContactListPresenter { */ onDeleteDialogConfirm(index, item) { HiLog.i(TAG, 'onDeleteDialogConfirm !!! '); - ContactRepository.getInstance().deleteById(item.contactId, (result) => { - HiLog.i(TAG, 'onDeleteDialogConfirm result is ' + JSON.stringify(result)); + this.worker.sendRequest("deleteContactById", { + context: this.context, + contactId: item.contactId + }, (result) => { + if (result) { + HiLog.w(TAG, "deleteContactById error:" + JSON.stringify(result)) + } ContactRepository.getInstance().notifyChange(); - CallLogRepository.getInstance().notifyChange(); }); + this.contactListDataSource.remove(index); } /** diff --git a/entry/src/main/ets/presenter/contact/accountants/AccountantsPresenter.ets b/entry/src/main/ets/presenter/contact/accountants/AccountantsPresenter.ets index c7a9631..831985f 100644 --- a/entry/src/main/ets/presenter/contact/accountants/AccountantsPresenter.ets +++ b/entry/src/main/ets/presenter/contact/accountants/AccountantsPresenter.ets @@ -105,48 +105,52 @@ export default class AccountantsPresenter { } isExistenceInfo(afterInfo: any) { - let flag = false; - flag = flag || !StringUtil.isEmpty(afterInfo.display_name); - flag = flag || !StringUtil.isEmpty(afterInfo.nickname); - flag = flag || !StringUtil.isEmpty(afterInfo.remarks); - flag = flag || !StringUtil.isEmpty(afterInfo.position); - flag = flag || !StringUtil.isEmpty(afterInfo.company); - if (!ArrayUtil.isEmpty(afterInfo.phones)) { - for (let item of afterInfo.phones) { - flag = flag || !StringUtil.isEmpty(item.num); + if (!afterInfo) { + return false; + } else { + let flag = false; + flag = flag || !StringUtil.isEmpty(afterInfo.display_name); + flag = flag || !StringUtil.isEmpty(afterInfo.nickname); + flag = flag || !StringUtil.isEmpty(afterInfo.remarks); + flag = flag || !StringUtil.isEmpty(afterInfo.position); + flag = flag || !StringUtil.isEmpty(afterInfo.company); + if (!ArrayUtil.isEmpty(afterInfo.phones)) { + for (let item of afterInfo.phones) { + flag = flag || !StringUtil.isEmpty(item?.num); + } } - } - if (!ArrayUtil.isEmpty(afterInfo.emails)) { - for (let item of afterInfo.emails) { - flag = flag || !StringUtil.isEmpty(item.address); + if (!ArrayUtil.isEmpty(afterInfo.emails)) { + for (let item of afterInfo.emails) { + flag = flag || !StringUtil.isEmpty(item?.address); + } } - } - if (!ArrayUtil.isEmpty(afterInfo.aims)) { - for (let item of afterInfo.aims) { - flag = flag || !StringUtil.isEmpty(item.aimName); + if (!ArrayUtil.isEmpty(afterInfo.aims)) { + for (let item of afterInfo.aims) { + flag = flag || !StringUtil.isEmpty(item?.aimName); + } } - } - if (!ArrayUtil.isEmpty(afterInfo.houses)) { - for (let item of afterInfo.houses) { - flag = flag || !StringUtil.isEmpty(item.houseName); + if (!ArrayUtil.isEmpty(afterInfo.houses)) { + for (let item of afterInfo.houses) { + flag = flag || !StringUtil.isEmpty(item?.houseName); + } } - } - if (!ArrayUtil.isEmpty(afterInfo.websites)) { - for (let item of afterInfo.websites) { - flag = flag || !StringUtil.isEmpty(item); + if (!ArrayUtil.isEmpty(afterInfo.websites)) { + for (let item of afterInfo.websites) { + flag = flag || !StringUtil.isEmpty(item); + } } - } - if (!ArrayUtil.isEmpty(afterInfo.events)) { - for (let item of afterInfo.events) { - flag = flag || !StringUtil.isEmpty(item.data); + if (!ArrayUtil.isEmpty(afterInfo.events)) { + for (let item of afterInfo.events) { + flag = flag || !StringUtil.isEmpty(item?.data); + } } - } - if (!ArrayUtil.isEmpty(afterInfo.relationships)) { - for (let item of afterInfo.relationships) { - flag = flag || !StringUtil.isEmpty(item.name); + if (!ArrayUtil.isEmpty(afterInfo.relationships)) { + for (let item of afterInfo.relationships) { + flag = flag || !StringUtil.isEmpty(item?.name); + } } + return flag; } - return flag; } getPageData(id: string) { @@ -526,45 +530,50 @@ export default class AccountantsPresenter { } public menuChange(typeName: string, data: any, item: any) { - switch (typeName) { - case "phone": - if (ObjectUtil.isEmpty(this.contactInfoAfter.phones[data.i - 1])) { - this.contactInfoAfter.phones[data.i - 1] = new PhoneNumBean("", "", "", "", ""); - } - this.contactInfoAfter.phones[data.i - 1].numType = item.rawValue.toString(); - break; - case "email": - if (ObjectUtil.isEmpty(this.contactInfoAfter.emails[data.i - 1])) { - this.contactInfoAfter.emails[data.i - 1] = new EmailBean("", "", ""); - } - this.contactInfoAfter.emails[data.i - 1].emailType = item.rawValue.toString(); - break; - case "AIM": - if (ObjectUtil.isEmpty(this.contactInfoAfter.aims[data.i - 1])) { - this.contactInfoAfter.aims[data.i - 1] = new AIMBean("", "", "", ""); - } - this.contactInfoAfter.aims[data.i - 1].aimType = item.rawValue.toString(); - break; - case "house": - if (ObjectUtil.isEmpty(this.contactInfoAfter.houses[data.i - 1])) { - this.contactInfoAfter.houses[data.i - 1] = new HouseBean("", "", "", ""); - } - this.contactInfoAfter.houses[data.i - 1].houseType = item.rawValue.toString(); - break; - case "relationships": - if (ObjectUtil.isEmpty(this.contactInfoAfter.relationships[data.i - 1])) { - this.contactInfoAfter.relationships[data.i - 1] = new AssociatedPersonBean("", "", "", ""); - } - this.contactInfoAfter.relationships[data.i - 1].associatedType = item.rawValue.toString(); - break; - case "events": - if (ObjectUtil.isEmpty(this.contactInfoAfter.events[data.i - 1])) { - this.contactInfoAfter.events[data.i - 1] = new EventBean("", "", "", ""); - } - this.contactInfoAfter.events[data.i - 1].eventType = item.rawValue.toString(); - break; - default: - break; + if (data.i) { + switch (typeName) { + case "phone": + if (ObjectUtil.isEmpty(this.contactInfoAfter.phones[data.i - 1])) { + this.contactInfoAfter.phones[data.i - 1] = new PhoneNumBean("", "", "", "", ""); + } + this.contactInfoAfter.phones[data.i - 1].numType = item.rawValue.toString(); + break; + case "email": + if (ObjectUtil.isEmpty(this.contactInfoAfter.emails[data.i - 1])) { + this.contactInfoAfter.emails[data.i - 1] = new EmailBean("", "", ""); + } + this.contactInfoAfter.emails[data.i - 1].emailType = item.rawValue.toString(); + break; + case "AIM": + if (ObjectUtil.isEmpty(this.contactInfoAfter.aims[data.i - 1])) { + this.contactInfoAfter.aims[data.i - 1] = new AIMBean("", "", "", ""); + } + this.contactInfoAfter.aims[data.i - 1].aimType = item.rawValue.toString(); + break; + case "house": + if (ObjectUtil.isEmpty(this.contactInfoAfter.houses[data.i - 1])) { + this.contactInfoAfter.houses[data.i - 1] = new HouseBean("", "", "", ""); + } + this.contactInfoAfter.houses[data.i - 1].houseType = item.rawValue.toString(); + break; + case "relationships": + if (ObjectUtil.isEmpty(this.contactInfoAfter.relationships[data.i - 1])) { + this.contactInfoAfter.relationships[data.i - 1] = new AssociatedPersonBean("", "", "", ""); + } + this.contactInfoAfter.relationships[data.i - 1].associatedType = item.rawValue.toString(); + break; + case "events": + if (ObjectUtil.isEmpty(this.contactInfoAfter.events[data.i - 1])) { + this.contactInfoAfter.events[data.i - 1] = new EventBean("", "", "", ""); + } + this.contactInfoAfter.events[data.i - 1].eventType = item.rawValue.toString(); + break; + default: + break; + } + } else { + HiLog.e(TAG, "data.i is Empty!" + JSON.stringify(data)); + return; } this.addState = true; this.refresh(); @@ -614,8 +623,12 @@ export default class AccountantsPresenter { } public getAddState() { - if (this.contactInfoAfter) { - return this.addState && this.isExistenceInfo(this.contactInfoAfter); + try { + if (this.contactInfoAfter) { + return this.addState && this.isExistenceInfo(this.contactInfoAfter); + } + } catch (err) { + HiLog.i(TAG, "something err: " + JSON.stringify(err)); } } diff --git a/entry/src/main/ets/presenter/dialer/callRecord/CallRecordPresenter.ets b/entry/src/main/ets/presenter/dialer/callRecord/CallRecordPresenter.ets index df9de3e..7f5115d 100644 --- a/entry/src/main/ets/presenter/dialer/callRecord/CallRecordPresenter.ets +++ b/entry/src/main/ets/presenter/dialer/callRecord/CallRecordPresenter.ets @@ -13,19 +13,18 @@ * limitations under the License. */ -import { HiLog } from '../../../../../../../common/src/main/ets/util/HiLog'; -import { ObjectUtil } from '../../../../../../../common/src/main/ets/util/ObjectUtil'; +import { HiLog, ArrayUtil } from '../../../../../../../common'; import { PhoneNumber } from '../../../../../../../feature/phonenumber/src/main/ets/PhoneNumber'; -import { ArrayUtil } from '../../../../../../../common/src/main/ets/util/ArrayUtil'; import router from '@ohos.router'; import { CallLogRepository } from '../../../../../../../feature/call'; import { ContactRepository } from '../../../../../../../feature/contact/src/main/ets/repo/ContactRepository'; import CallRecordListDataSource from './../../../model/bean/CallRecordListDataSource'; import CallLogSetting from '../../../../../../../feature/call/src/main/ets/CallLogSetting' import DialerPresenter from '../../../presenter/dialer/DialerPresenter'; -import emitter from '@ohos.events.emitter'; +import WorkerWrapper from '../../../workers/base/WorkerWrapper'; const TAG = 'CallRecordPresenter' +const DELAY_TIME: number = 1000; export default class CallRecordPresenter { private static mPresenter: CallRecordPresenter; @@ -33,54 +32,240 @@ export default class CallRecordPresenter { mMissCallRecordListDataSource: CallRecordListDataSource = new CallRecordListDataSource(); mDialerPresent: DialerPresenter = DialerPresenter.getInstance(); isShow: boolean = false; + page: number = 0; + limit: number = 0; + context: Context; + worker: WorkerWrapper; + refreshState: () => void + loading: boolean = false; + callLogListPages: Array = []; + missedListPages: Array = []; + callLogIndex: number = 0; + missedIndex: number = 0; + tabIndex: number = 0; + initStarted: boolean = false; + taskId: number = undefined; + onCallsChange = () => { + HiLog.i(TAG, 'onCallsChange refresh'); + this.setDelayTask(); + } + onContactChange = () => { + HiLog.i(TAG, 'onContactChange refresh'); + this.setDelayTask(); + } static getInstance() { + if (globalThis.presenterManager?.callRecordPresenter) { + return globalThis.presenterManager.callRecordPresenter; + } if (CallRecordPresenter.mPresenter == null) { CallRecordPresenter.mPresenter = new CallRecordPresenter(); } return CallRecordPresenter.mPresenter; } - onPageShow() { - HiLog.i(TAG, 'onPageShow'); - this.isShow = true; + bindUI(refreshState?: () => void) { + this.refreshState = refreshState; } - onPageHide() { - HiLog.i(TAG, 'onPageHide'); - this.isShow = false; + onCreate(context: Context, worker: WorkerWrapper) { + this.context = context; + this.worker = worker; + CallLogRepository.getInstance().registerDataChangeObserver(this.onCallsChange); + ContactRepository.getInstance().registerDataChangeObserver(this.onContactChange); + } + + onDestroy() { + CallLogRepository.getInstance().unRegisterDataChangeObserver(this.onCallsChange); + ContactRepository.getInstance().unRegisterDataChangeObserver(this.onContactChange); + } + + startInit() { + if (this.initStarted) { + return; + } + HiLog.i(TAG, "startInit"); + this.initStarted = true; + if (this.page == 0) { + this.page++; + } + this.refreshContinue(); + } + + cachePageOne() { + if (!this.initStarted && !this.loading) { + HiLog.i(TAG, "cachePageOne") + this.page = 1; + this.callLogIndex = 0; + this.missedIndex = 0; + this.refreshContinue(); + } else { + HiLog.i(TAG, "no need cachePageOne"); + } + } + + setPageShow(isShow: boolean) { + if (this.isShow == isShow) { + return; + } + this.isShow = isShow; + if (this.isShow) { + this.startInit(); + } + this.setTabShow(); } aboutToAppear() { HiLog.i(TAG, 'aboutToAppear!'); - this.isShow = true; + this.startInit(); } aboutToDisappear() { HiLog.i(TAG, 'aboutToDisappear!'); - this.isShow = false; } - refreshMissedList(missedList) { - HiLog.i(TAG, 'refreshMissedList, length is ' + missedList.length); - if (!ObjectUtil.isEmpty(this.mMissCallRecordListDataSource)) { - this.mMissCallRecordListDataSource.refresh(missedList); + setTabShow() { + if (this.isShow) { + HiLog.i(TAG, 'setTabShow:' + this.tabIndex); + if (this.tabIndex == 0) { + this.mMissCallRecordListDataSource.setIsShow(false); + this.mAllCallRecordListDataSource.setIsShow(true); + } else { + this.mAllCallRecordListDataSource.setIsShow(false); + this.mMissCallRecordListDataSource.setIsShow(true); + } + } else { + this.mAllCallRecordListDataSource.setIsShow(false); + this.mMissCallRecordListDataSource.setIsShow(false); } } - refreshCallLogList(callLogList) { - HiLog.i(TAG, 'refreshCallLogList, length is ' + callLogList.length); - if (!ObjectUtil.isEmpty(this.mAllCallRecordListDataSource)) { - this.mAllCallRecordListDataSource.refresh(callLogList); + setTabIndex(index) { + if (this.tabIndex != index) { + this.tabIndex = index; + this.setTabShow(); + } + } + + requestItem() { + HiLog.i(TAG, 'CallLogs requestItem!'); + if (this.page == 0) { + this.page++; + this.refreshContinue(); + } else if (!this.initStarted && !this.loading) { + this.cachePageOne(); + } else { + HiLog.i(TAG, 'isLoading'); + } + } + + setDelayTask() { + if (this.taskId != undefined) { + clearTimeout(this.taskId); + this.taskId = undefined; + } + let delay: number = 0; + if (this.page != 0) { + delay += DELAY_TIME; + } + if (!this.isShow) { + delay += DELAY_TIME; + } + if (delay > 0) { + this.taskId = setTimeout(() => { + if (this.page != 0) { + this.setDelayTask(); + } else { + this.requestItem(); + } + }, delay); + } else { + this.requestItem(); + } + } + + refreshContinue() { + if (this.loading) { + HiLog.i(TAG, 'refreshContinue is loading'); + return; + } + if (this.page == 0) { + HiLog.i(TAG, 'refreshContinue end'); + return; + } + if (this.page == 1) { + this.limit = 50; + } else { + this.limit = 500; + } + this.refreshPage(this.page, this.limit, () => { + if (this.initStarted) { + setTimeout(() => { + this.refreshContinue(); + },!this.isShow ? 700 : 1); + } + }) + } + + refreshPage(page: number, limit: number, callback?: () => void) { + this.loading = true; + let actionData: any = {}; + actionData.page = page; + actionData.limit = limit; + this.worker?.sendRequest("getAllCalls", { + context: this.context, + mergeRule: CallLogSetting.getInstance().getMergeRule(), + actionData: actionData + }, (data) => { + let dateLength = data.callLogList.length; + HiLog.i(TAG, `refreshPage ${page} and getAllCalls, length is ` + dateLength); + if (Array.prototype.isPrototypeOf(data.callLogList)) { + this.mAllCallRecordListDataSource.refresh(this.callLogIndex, this.callLogListPages[page-1], data.callLogList); this.mDialerPresent.refresh(); } + if (Array.prototype.isPrototypeOf(data.missedList)) { + this.mMissCallRecordListDataSource.refresh(this.missedIndex, this.missedListPages[page - 1], data.missedList); + } + this.callLogListPages[page-1] = dateLength; + this.callLogIndex += this.callLogListPages[page-1]; + this.missedListPages[page - 1] = data.missedList.length; + this.missedIndex += this.missedListPages[page - 1]; + if (this.refreshState) { + this.refreshState(); + } + if (dateLength < limit) { + this.page = 0; + HiLog.i(TAG, 'CallLogs load completed: ' + JSON.stringify(this.mAllCallRecordListDataSource.totalCount())); + if (this.callLogListPages.length > page) { + this.callLogListPages.splice(page, this.callLogListPages.length - page); + } + if (this.missedListPages.length > page) { + this.missedListPages.splice(page, this.missedListPages.length - page); + } + if (this.mAllCallRecordListDataSource.totalCount() > this.callLogIndex) { + this.mAllCallRecordListDataSource.remove(this.callLogIndex, this.mAllCallRecordListDataSource.totalCount() - this.callLogIndex); + } + if (this.mMissCallRecordListDataSource.totalCount() > this.missedIndex) { + this.mMissCallRecordListDataSource.remove(this.missedIndex, this.mMissCallRecordListDataSource.totalCount() - this.missedIndex); + } + this.callLogIndex = 0; + this.missedIndex = 0; + this.loading = false; + } else { + this.page = page + 1; + this.loading = false; + if (callback) { + callback(); + } + } + }) } dialing(phoneNumber, options?: any) { PhoneNumber.fromString(phoneNumber).dial(options); } - deleteCallLog(id) { + deleteCallLog(id, index?) { globalThis.DataWorker.sendRequest("deleteCallLogsById", { context: globalThis.context, ids: id @@ -88,6 +273,13 @@ export default class CallRecordPresenter { HiLog.i(TAG, 'deleteCallLog Success'); CallLogRepository.getInstance().notifyChange() }); + if (index != undefined) { + if (this.tabIndex == 0) { + this.mAllCallRecordListDataSource.remove(index); + } else { + this.mMissCallRecordListDataSource.remove(index); + } + } } jumpToContactDetail(phoneNumber) { diff --git a/entry/src/main/ets/service/CallsService.ets b/entry/src/main/ets/service/CallsService.ets index d82d929..36b4842 100644 --- a/entry/src/main/ets/service/CallsService.ets +++ b/entry/src/main/ets/service/CallsService.ets @@ -1,17 +1,3 @@ -/** - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ import { CallLogRepository } from '../../../../../feature/call'; import { ContactRepository } from '../../../../../feature/contact'; import { HiLog, ArrayUtil } from '../../../../../common'; diff --git a/entry/src/main/ets/service/ContactsService.ets b/entry/src/main/ets/service/ContactsService.ets index a29dbf1..437c36d 100644 --- a/entry/src/main/ets/service/ContactsService.ets +++ b/entry/src/main/ets/service/ContactsService.ets @@ -1,17 +1,3 @@ -/** - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ import { ContactRepository } from '../../../../../feature/contact'; import { HiLog, ArrayUtil } from '../../../../../common'; import { ContactVo } from '../model/bean/ContactVo'; diff --git a/entry/src/main/ets/util/CalendarUtil.ets b/entry/src/main/ets/util/CalendarUtil.ets index de99add..6c419ef 100644 --- a/entry/src/main/ets/util/CalendarUtil.ets +++ b/entry/src/main/ets/util/CalendarUtil.ets @@ -1,5 +1,5 @@ /** - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import i18n from '@ohos.i18n'; const YEAR_CONVERT: number = 2697; diff --git a/entry/src/main/ets/workers/AudioWorker.js b/entry/src/main/ets/workers/AudioWorker.js deleted file mode 100644 index 8f27725..0000000 --- a/entry/src/main/ets/workers/AudioWorker.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import worker from '@ohos.worker'; -import media from '@ohos.multimedia.media'; -import Log from "@ohos.hilog"; - -/** - * dailpad key tone worker - */ -const parentPort = worker.parentPort; -const TAG = "ContactLog"; -const DOMAIN = 0x0900; -let audioPlayer = undefined; -let mAudioPath = ''; - -parentPort.onmessage = function (e) { - let data = e.data; - switch (data.type) { - case "audio": - if (audioPlayer == undefined) { - audioPlayer = media.createAudioPlayer(); - audioPlayer.on('dataLoad', () => { - audioPlayer.play(); - }); - } - let fileName = data.data; - console.log(`fileName is ${JSON.stringify(fileName)}`) - if (mAudioPath == '') { - audioPlayer.fdSrc = fileName; - } else if (mAudioPath == fileName) { - audioPlayer.seek(0); - audioPlayer.play(); - } else { - audioPlayer.reset(); - audioPlayer.fdSrc = fileName; - } - mAudioPath = fileName; - break; - case "over": - audioPlayer.release(); - audioPlayer = undefined; - parentPort.close(); - break; - default: - Log.error(DOMAIN, TAG, 'the case is not in this category'); - break; - } -} \ No newline at end of file diff --git a/entry/src/main/ets/workers/DataWorkerTask.ets b/entry/src/main/ets/workers/DataWorkerTask.ets new file mode 100644 index 0000000..6b30286 --- /dev/null +++ b/entry/src/main/ets/workers/DataWorkerTask.ets @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { HiLog } from "../../../../../common" +import { WorkerType } from "./WorkFactory" +import WorkerWrapper from "./base/WorkerWrapper" +import WorkerTask from "./base/WorkerTask" +import { ThreadWorkerGlobalScope } from '@ohos.worker'; +import CallLog from '../model/calllog/CalllogModel'; +import { CallLogRepository } from '../../../../../feature/call'; +import { ContactRepository } from '../../../../../feature/contact'; +import ContactAbilityModel from '../model/ContactAbilityModel'; + +const TAG = "DataWorkerTask" + + +export enum DataWorkerConstant { + "deleteCallLogsById", + "getAllCalls", + "findByNumberIn", + "deleteContactById", + "addContact", + "getAllContact", + "getAllContactWithPhoneNumbers", + "getContactById", + "updateContact", + "getIdByTelephone", +} + +export class DataWorkerTask extends WorkerTask { + private static sInstance: DataWorkerTask = undefined; + + private constructor(workerPort: ThreadWorkerGlobalScope) { + super(workerPort) + } + + static getInstance(workerPort: ThreadWorkerGlobalScope) { + HiLog.i(TAG, "getInstance in.") + if (DataWorkerTask.sInstance == undefined || DataWorkerTask.sInstance.workerPort == undefined) { + DataWorkerTask.sInstance = new DataWorkerTask(workerPort); + } + return DataWorkerTask.sInstance; + } + + runInWorker(request: string, callBack: (v?: any) => void, param?: any) { + HiLog.i(TAG, `runInWorker ${request}`) + switch (request) { + case DataWorkerConstant[DataWorkerConstant.getAllCalls]: + CallLog.getAllCalls(param.actionData, param.mergeRule, (data) => { + HiLog.i(TAG, `getAllCalls result: ${JSON.stringify(data).length}`) + callBack(data); + }, param.context); + break; + case DataWorkerConstant[DataWorkerConstant.findByNumberIn]: + CallLogRepository.getInstance().init(param.context); + CallLogRepository.getInstance().findByNumberIn(param.numbers, (resultList) => { + callBack(resultList); + }); + break + case DataWorkerConstant[DataWorkerConstant.deleteContactById]: + ContactRepository.getInstance().init(param.context); + ContactRepository.getInstance().deleteById(param.contactId, (result) => { + HiLog.i(TAG, `deleteContactById result ${result}`) + callBack(result); + }); + break; + case DataWorkerConstant[DataWorkerConstant.deleteCallLogsById]: + CallLogRepository.getInstance().init(param.context); + CallLogRepository.getInstance().deleteByIdIn(param.ids, (result) => { + callBack(result); + }) + break; + case DataWorkerConstant[DataWorkerConstant.addContact]: + const contactInfoAfter = JSON.parse(param.contactInfoAfter) + ContactAbilityModel.addContact(contactInfoAfter, (arg) => { + callBack(arg); + }, param.context) + break + case DataWorkerConstant[DataWorkerConstant.getAllContact]: + ContactAbilityModel.getAllContact(param.actionData, (result) => { + callBack(result); + }, param.context) + break + case DataWorkerConstant[DataWorkerConstant.getAllContactWithPhoneNumbers]: + ContactAbilityModel.getAllContactWithPhoneNumbers((resultList) => { + callBack(resultList); + }, param.context) + break + case DataWorkerConstant[DataWorkerConstant.getContactById]: + ContactAbilityModel.getContactById(param.contactId, result => { + callBack(result); + }, param.context) + break + case DataWorkerConstant[DataWorkerConstant.getIdByTelephone]: + ContactAbilityModel.getIdByTelephone(param.phoneNumber, (contactId) => { + callBack(contactId); + }, param.context) + break + case DataWorkerConstant[DataWorkerConstant.updateContact]: + ContactAbilityModel.updateContact(null, JSON.parse(param.contactInfoAfter), (arg) => { + callBack(arg); + }, param.context) + break + default: + HiLog.w(TAG, `${request} not allow!!!`) + break; + } + } +} \ No newline at end of file diff --git a/entry/src/main/ets/workers/WorkFactory.ets b/entry/src/main/ets/workers/WorkFactory.ets index f7a077a..bbefb08 100644 --- a/entry/src/main/ets/workers/WorkFactory.ets +++ b/entry/src/main/ets/workers/WorkFactory.ets @@ -15,7 +15,7 @@ import { ThreadWorkerGlobalScope, MessageEvents } from '@ohos.worker'; import { HiLog } from "../../../../../common" -import DataWorkerWrapper, { DataWorkerTask } from "./DataWorkerWrapper" +import { DataWorkerTask } from "./DataWorkerTask" import WorkerWrapper, { WorkerMessage } from "./base/WorkerWrapper" import WorkerTask from "./base/WorkerTask" @@ -33,13 +33,10 @@ export default class WorkFactory { * @param message worker message data * @return WorkerTask for the message */ - static getTask(workerPort: ThreadWorkerGlobalScope, message: MessageEvents): WorkerTask { - let data = message.data; - let type = data.type; + static getTask(type: WorkerType, workerPort?: ThreadWorkerGlobalScope): WorkerTask { HiLog.i(TAG, `getTask in ${WorkerType[type]}.`) let task: WorkerTask = undefined; if (type == WorkerType.DataWorker) { - HiLog.w(TAG, "getTask " + type) task = DataWorkerTask.getInstance(workerPort); } HiLog.w(TAG, "getTask end") @@ -57,7 +54,7 @@ export default class WorkFactory { let worker: WorkerWrapper = undefined if (type == WorkerType.DataWorker) { HiLog.w(TAG, "getWorker " + type) - worker = DataWorkerWrapper.getInstance(); + worker = new WorkerWrapper(WorkerType.DataWorker, globalThis.config.useDataWorker); } HiLog.w(TAG, "getWorker end") return worker; diff --git a/entry/src/main/ets/workers/base/Worker.ts b/entry/src/main/ets/workers/base/Worker.ts index 2d5e42a..199004d 100644 --- a/entry/src/main/ets/workers/base/Worker.ts +++ b/entry/src/main/ets/workers/base/Worker.ts @@ -28,7 +28,9 @@ const TAG = "Worker"; workerPort.onmessage = function (e: MessageEvents) { HiLog.w(TAG, "onmessage"); if (e.data) { - let task = WorkFactory.getTask(workerPort, e) + let data = e.data; + let type = data.type; + let task = WorkFactory.getTask(type, workerPort) task?.onmessage(e); } else { HiLog.w(TAG, `onmessage ${JSON.stringify(e)} not allow`) diff --git a/entry/src/main/ets/workers/base/WorkerTask.ts b/entry/src/main/ets/workers/base/WorkerTask.ts index bf1f3d0..9b8d125 100644 --- a/entry/src/main/ets/workers/base/WorkerTask.ts +++ b/entry/src/main/ets/workers/base/WorkerTask.ts @@ -27,7 +27,7 @@ const TAG = "WorkerTask" export abstract class WorkerTask { workerPort: ThreadWorkerGlobalScope - constructor(workerPort: ThreadWorkerGlobalScope) { + constructor(workerPort?: ThreadWorkerGlobalScope) { HiLog.i(TAG, `WorkerTask constructor`) this.workerPort = workerPort; } @@ -39,20 +39,19 @@ export abstract class WorkerTask { * @param e message data */ public onmessage(message: MessageEvents) { - let data = message.data - HiLog.i(TAG, `onmessage ${data.request}`) try { + let data = message.data + HiLog.i(TAG, `onmessage ${data.request}`) this.runInWorker(data.request, (v) => { HiLog.i(TAG, "runInWorker callback in") data.param = v; const str = JSON.stringify(data) let buf = buffer.from(str).buffer; - this.workerPort.postMessage(buf, [buf]); + this.workerPort?.postMessage(buf, [buf]); }, data.param); } catch (err) { HiLog.e(TAG, 'runInWorker err = ' + JSON.stringify(err)); } - } public abstract runInWorker(request: string, callBack: (v?: any) => void, param?: any); diff --git a/entry/src/main/ets/workers/base/WorkerWrapper.ts b/entry/src/main/ets/workers/base/WorkerWrapper.ts index 1ab09ae..4f84b88 100644 --- a/entry/src/main/ets/workers/base/WorkerWrapper.ts +++ b/entry/src/main/ets/workers/base/WorkerWrapper.ts @@ -13,7 +13,7 @@ * limitations under the License. */ -import { WorkerType } from "../WorkFactory" +import WorkFactory, { WorkerType } from "../WorkFactory" import worker from '@ohos.worker'; import { HiLog } from "../../../../../../common" import buffer from "@ohos.buffer" @@ -21,10 +21,10 @@ import buffer from "@ohos.buffer" const TAG = "WorkerWrapper" export class WorkerMessage { - request: string; - callBackId: number; - type?: WorkerType; - param?: any; + request: string; + callBackId: number; + type?: WorkerType; + param?: any; } /* @@ -32,92 +32,100 @@ export class WorkerMessage { * * Processes sending tasks to workers and receiving work processing results. */ -export abstract class WorkerWrapper { - protected mWorker: worker.ThreadWorker = undefined; - private callBacks: Map void> = new Map(); - private requestIndex: number = 0; +export default class WorkerWrapper { + protected mWorker: worker.ThreadWorker = undefined; + private callBacks: Map void> = new Map(); + private requestIndex: number = 0; + private workType: WorkerType; + private useWorker: boolean; - constructor() { - this.initWorker(); + constructor(workType: WorkerType, useWorker: boolean) { + this.workType = workType; + this.useWorker = useWorker; + if (useWorker) { + this.initWorker(); } + } - async initWorker() { - HiLog.i(TAG, `WorkerWrapper initWorker ${WorkerType[this.getWorkerType()]}`) - let initWorker = await new worker.ThreadWorker("entry/ets/workers/base/Worker.ts", { - name: WorkerType[this.getWorkerType()] - }); - let that = this; - initWorker.onexit = function (message) { - HiLog.w(TAG, "onexit") - that.mWorker = undefined; - } - initWorker.onerror = function (e) { - HiLog.w(TAG, "onerror:" + JSON.stringify(e)) - } - initWorker.onmessageerror = function (e) { - HiLog.w(TAG, "onmessageerror:" + JSON.stringify(e)) - } - initWorker.onmessage = function (message) { - const buff = message.data; - const str = buffer.from(buff).toString(); - let data = JSON.parse(str) - HiLog.i(TAG, `onmessage ${data.request}`) - const key = that.getCallBackKey(data); - if (that.callBacks.has(key)) { - HiLog.i(TAG, `onmessage notify result.`) - const callback = that.callBacks.get(key); - if (callback) { - callback(data.param); - } - that.callBacks.delete(key); - } - } - this.mWorker = initWorker; - HiLog.i(TAG, `WorkerWrapper initWorker end`) + async initWorker() { + HiLog.i(TAG, `WorkerWrapper initWorker ${WorkerType[this.getWorkerType()]}`) + let initWorker = await new worker.ThreadWorker("entry/ets/workers/base/Worker.ts", { + name: WorkerType[this.getWorkerType()] + }); + let that = this; + initWorker.onexit = function (message) { + HiLog.w(TAG, "onexit") + that.mWorker = undefined; } - - public abstract getWorkerType(): WorkerType; - - /** - * SendRequest to worker thread. - * - * @param {string} request the request worker to do - * @param {Object} requestData request param Data - * @param {Object} callBack Call back from worker - */ - public async sendRequest(request: string, requestData?: any, callBack?: (result?: any) => void) { - HiLog.i(TAG, "sendRequest in " + request) - if (this.mWorker) { - const message = { - request: request, - callBackId: this.requestIndex, - type: this.getWorkerType(), - param: requestData - } - if (callBack) { - this.callBacks.set(this.getCallBackKey(message), callBack); - } - this.mWorker?.postMessage(message); - HiLog.d(TAG, `${this.getWorkerType()} ${request} send succ!`); - this.requestIndex++; - } else { - HiLog.w(TAG, `${this.getWorkerType()} ${request} send fail, worker has been closed!`); + initWorker.onerror = function (e) { + HiLog.w(TAG, "onerror:" + JSON.stringify(e)) + } + initWorker.onmessageerror = function (e) { + HiLog.w(TAG, "onmessageerror:" + JSON.stringify(e)) + } + initWorker.onmessage = function (message) { + const buff = message.data; + const str = buffer.from(buff).toString(); + let data = JSON.parse(str) + HiLog.i(TAG, `onmessage ${data.request}`) + const key = that.getCallBackKey(data); + if (that.callBacks.has(key)) { + HiLog.i(TAG, `onmessage notify result.`) + const callback = that.callBacks.get(key); + if (callback) { + callback(data.param); } + that.callBacks.delete(key); + } } + this.mWorker = initWorker; + HiLog.i(TAG, `WorkerWrapper initWorker end`) + } - /** - * Close close worker thread. - */ - public close() { - HiLog.i(TAG, `${this.getWorkerType()} worker close!`); - this.mWorker?.terminate(); - this.mWorker = undefined; - this.callBacks.clear(); - } + public getWorkerType(): WorkerType { + return this.workType; + } - private getCallBackKey(message: WorkerMessage): string { - return message.request + message.callBackId; + /** + * SendRequest to worker thread. + * + * @param {string} request the request worker to do + * @param {Object} requestData request param Data + * @param {Object} callBack Call back from worker + */ + public async sendRequest(request: string, requestData?: any, callBack?: (result?: any) => void) { + HiLog.i(TAG, "sendRequest in " + request) + if (!this.useWorker) { + WorkFactory.getTask(this.getWorkerType()).runInWorker(request, callBack, requestData); + } else if (this.mWorker) { + const message = { + request: request, + callBackId: this.requestIndex, + type: this.getWorkerType(), + param: requestData + } + if (callBack) { + this.callBacks.set(this.getCallBackKey(message), callBack); + } + this.mWorker?.postMessage(message); + HiLog.d(TAG, `${this.getWorkerType()} ${request} send succ!`); + this.requestIndex++; + } else { + HiLog.w(TAG, `${this.getWorkerType()} ${request} send fail, worker has been closed!`); } + } + + /** + * Close close worker thread. + */ + public close() { + HiLog.i(TAG, `${this.getWorkerType()} worker close!`); + this.mWorker?.terminate(); + this.mWorker = undefined; + this.callBacks.clear(); + } + + private getCallBackKey(message: WorkerMessage): string { + return message.request + message.callBackId; + } } - -export default WorkerWrapper; \ No newline at end of file diff --git a/entry/src/main/module.json5 b/entry/src/main/module.json5 index 3a744e5..ad9076a 100644 --- a/entry/src/main/module.json5 +++ b/entry/src/main/module.json5 @@ -25,7 +25,7 @@ "description": "$string:mainability_description", "icon": "$media:ic_contact_icon", "label": "$string:app_name", - "startWindowIcon": "$media:icon", + "startWindowIcon": "$media:white", "startWindowBackground": "$color:detail_main_background", "minWindowWidth": 320, "minWindowHeight": 700, diff --git a/entry/src/main/resources/base/element/bool.json b/entry/src/main/resources/base/element/bool.json new file mode 100644 index 0000000..d799d02 --- /dev/null +++ b/entry/src/main/resources/base/element/bool.json @@ -0,0 +1,12 @@ +{ + "boolean": [ + { + "name": "cache_page_one", + "value": true + }, + { + "name": "use_data_worker", + "value": true + } + ] +} \ No newline at end of file diff --git a/entry/src/main/resources/base/media/dial_single_button_hd.svg b/entry/src/main/resources/base/media/dial_single_button_hd.svg new file mode 100644 index 0000000..455b312 --- /dev/null +++ b/entry/src/main/resources/base/media/dial_single_button_hd.svg @@ -0,0 +1,7 @@ + + + dial_single_button_12 + + + + \ No newline at end of file diff --git a/entry/src/main/resources/base/media/ic_contact_call_1_hd_dial.svg b/entry/src/main/resources/base/media/ic_contact_call_1_hd_dial.svg new file mode 100644 index 0000000..ab4d1f0 --- /dev/null +++ b/entry/src/main/resources/base/media/ic_contact_call_1_hd_dial.svg @@ -0,0 +1,8 @@ + + + ic_contact_call_1_hd_dial + + + + + \ No newline at end of file diff --git a/entry/src/main/resources/base/media/ic_contact_call_2_hd_dial.svg b/entry/src/main/resources/base/media/ic_contact_call_2_hd_dial.svg new file mode 100644 index 0000000..b206630 --- /dev/null +++ b/entry/src/main/resources/base/media/ic_contact_call_2_hd_dial.svg @@ -0,0 +1,8 @@ + + + ic_contact_call_2_hd_dial + + + + + \ No newline at end of file diff --git a/entry/src/main/resources/base/media/white.PNG b/entry/src/main/resources/base/media/white.PNG new file mode 100644 index 0000000000000000000000000000000000000000..ee8349f886c1985b8298ec248fddb79bb826a9c3 GIT binary patch literal 123 zcmeAS@N?(olHy`uVBq!ia0vp^tU%1f!3HEJWQoNBDaPU;cPEB*=VV?2IV|apzK#qG z8~eHcB!X0O7I;J!GcfQS24TkI`72U@f&!i{jv*4^$v^s869oVKmuGP0SHD?#swoO6 O$KdJe=d#Wzp$Py9tsV&g literal 0 HcmV?d00001 diff --git a/feature/call/src/main/ets/missedcall/MissedCallNotifier.ets b/feature/call/src/main/ets/missedcall/MissedCallNotifier.ets index f84c849..9248f87 100644 --- a/feature/call/src/main/ets/missedcall/MissedCallNotifier.ets +++ b/feature/call/src/main/ets/missedcall/MissedCallNotifier.ets @@ -15,7 +15,6 @@ import Notification from "@ohos.notificationManager" import WantAgent from '@ohos.app.ability.wantAgent'; import { HiLog, sharedPreferencesUtils } from '../../../../../../common'; -var notificationManager = globalThis.requireNapi("notificationManager"); const TAG = "MissedCallNotifier"; @@ -112,6 +111,16 @@ export class MissedCallNotifier { }); } + /** + * get Missed Call BadgeNumber + */ + public async getMissedBadgeNumber() { + if (this.missedBadgeNumber == -1) { + this.missedBadgeNumber = await sharedPreferencesUtils.getFromPreferences(KEY_MISSED_BADGE_NUM, -1); + } + return this.missedBadgeNumber; + } + /** * cancel Missed Call Notification By NotificationId * @@ -122,12 +131,10 @@ export class MissedCallNotifier { Notification.cancel(id, this.label).catch(error => { HiLog.e(TAG, `cancelNotificationById,err ${JSON.stringify(error)}}`) }); - if (this.missedBadgeNumber == -1) { - let badgeNumber: number = await sharedPreferencesUtils.getFromPreferences(KEY_MISSED_BADGE_NUM, -1); - badgeNumber -= count; - if (badgeNumber >= 0) { - this.setMissedBadgeNumber(badgeNumber); - } + let badgeNumber = await this.getMissedBadgeNumber(); + badgeNumber -= count; + if (badgeNumber >= 0) { + this.setMissedBadgeNumber(badgeNumber); } } @@ -188,6 +195,7 @@ export class MissedCallNotifier { wantAgent: wantAgent }); } + notificationRequest.removalWantAgent = await this.createWantAgentForCommonEvent(missedCallData, "contact.event.CANCEL_MISSED"); Notification.publish(notificationRequest).then(() => { HiLog.i(TAG, '===>publish promise success req.id : ' + notificationRequest.id); }).catch((err) => { @@ -199,10 +207,26 @@ export class MissedCallNotifier { private setMissedBadgeNumber(newBadgeNum: number) { HiLog.i(TAG, 'setMissedBadgeNumber :' + newBadgeNum); this.missedBadgeNumber = newBadgeNum; - notificationManager.setBadgeNumber(newBadgeNum); + Notification.setBadgeNumber(newBadgeNum); sharedPreferencesUtils.saveToPreferences(KEY_MISSED_BADGE_NUM, newBadgeNum); } + /** + * create wantAgent for common event + * + * @param mAction + * @return return the created WantAgent object. + */ + private async createWantAgentForCommonEvent(missedCallData, action: string) { + return await WantAgent.getWantAgent({ + wants: [{ action: action, parameters: { + missedCallData: missedCallData + }, }], + operationType: WantAgent.OperationType.SEND_COMMON_EVENT, + requestCode: 0 // requestCodeWantAgentInfo룬ʹ߶һ˽ֵ + }) + } + private getWantAgent(missedCallData: MissedCallNotifyData, action: string) { let data: any = {} data.action = action, diff --git a/feature/call/src/main/ets/missedcall/MissedCallService.ets b/feature/call/src/main/ets/missedcall/MissedCallService.ets index fa47ba6..d38bfc0 100644 --- a/feature/call/src/main/ets/missedcall/MissedCallService.ets +++ b/feature/call/src/main/ets/missedcall/MissedCallService.ets @@ -81,7 +81,7 @@ export class MissedCallService { * @param data MissedCallNotifyData need cancel notify */ public async cancelMissedNotificationAction(data: MissedCallNotifyData) { - HiLog.i(TAG, `updateMissedCallNotifications, ${JSON.stringify(data)}`); + HiLog.i(TAG, `cancelMissedNotificationAction, ${JSON.stringify(data)}`); MissedCallNotifier.getInstance().cancelNotificationById(data.id, data.count); CallLogRepository.getInstance().markMissedCallLogAsRead(data.phoneNumber); } @@ -90,9 +90,12 @@ export class MissedCallService { * cancelAllMissedNotificationAction */ public async cancelAllMissedNotificationAction() { - HiLog.i(TAG, `cancelAllMissedNotificationAction cancel all`); - MissedCallNotifier.getInstance().cancelAllNotification(); - CallLogRepository.getInstance().markMissedCallLogAsRead(); + let unreadMissed = await MissedCallNotifier.getInstance().getMissedBadgeNumber() + if (unreadMissed > 0) { + HiLog.i(TAG, `cancelAllMissedNotificationAction cancel all`); + MissedCallNotifier.getInstance().cancelAllNotification(); + CallLogRepository.getInstance().markMissedCallLogAsRead(); + } } private constructor() { diff --git a/feature/phonenumber/src/main/ets/PhoneNumber.ets b/feature/phonenumber/src/main/ets/PhoneNumber.ets index 60738f2..853dd7e 100644 --- a/feature/phonenumber/src/main/ets/PhoneNumber.ets +++ b/feature/phonenumber/src/main/ets/PhoneNumber.ets @@ -39,10 +39,10 @@ export class PhoneNumber { return new Promise(function (resolve, reject) { call.isEmergencyPhoneNumber(phoneNumber, (err, data) => { if (err) { - HiLog.e(TAG, 'isEmergencyPhoneNumber error: ' + JSON.stringify(phoneNumber)); + HiLog.e(TAG, 'isEmergencyPhoneNumber error: ' + JSON.stringify(err)); reject(err); } else { - HiLog.e(TAG, 'isEmergencyPhoneNumber data: ' + JSON.stringify(data)); + HiLog.i(TAG, 'isEmergencyPhoneNumber data: ' + JSON.stringify(data)); resolve(data); } }); diff --git a/feature/phonenumber/src/main/ets/SharedPreferencesUtils.ets b/feature/phonenumber/src/main/ets/SharedPreferencesUtils.ets deleted file mode 100644 index de285ab..0000000 --- a/feature/phonenumber/src/main/ets/SharedPreferencesUtils.ets +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import data_preferences from '@ohos.data.preferences'; - -const NAME: string = "CONTACT_PREFERENCE"; -type ValueType = number | string | boolean | Array | Array | Array; - -class SharedPreferencesUtils { - private mPreferences: data_preferences.Preferences; - - constructor() { - this.getPreferences().then((data) => { - this.mPreferences = data; - }) - } - - /** - * getFromPreferences - * - * @return the value get from Preferences - */ - public async getFromPreferences(key: string, defValue) { - let preferences: data_preferences.Preferences = await this.getPreferences(); - return await preferences.get(key, defValue); - } - - /** - * saveToPreferences - * - * @param key save to Preferences - * @param value save to Preferences - */ - public async saveToPreferences(key: string, value: ValueType) { - let preferences: data_preferences.Preferences = await this.getPreferences(); - await preferences.put(key, value); - preferences.flush() - } - - private async getPreferences() { - if (this.mPreferences) { - return this.mPreferences; - } - return await data_preferences.getPreferences(globalThis.context, NAME); - } -} - -export default new SharedPreferencesUtils(); \ No newline at end of file diff --git a/feature/phonenumber/src/main/ets/SimUtil.ets b/feature/phonenumber/src/main/ets/SimUtil.ets deleted file mode 100644 index b6c96be..0000000 --- a/feature/phonenumber/src/main/ets/SimUtil.ets +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import observer from '@ohos.telephony.observer'; -import telephonySim from '@ohos.telephony.sim'; - -import { HiLog } from '../../../../../common/src/main/ets/util/HiLog'; -import SharedPreferencesUtils from "./SharedPreferencesUtils"; - -export const simId_NONE: number = -1; - -export const simId_ONE: number = 0; - -export const simId_TWO: number = 1; - -const INTERVAL = 1000; - -const TIME_OUT = 10; - -const KEY_LAST_ID: string = "last_used_sim_key" - -const TAG = 'SimUtil'; - -interface Observer { - (): void; -} - -class SimCardState { - mSimStateArray: Array = - [telephonySim.SimState.SIM_STATE_UNKNOWN, telephonySim.SimState.SIM_STATE_UNKNOWN]; - haveSimCard: boolean = false; - haveMultiSimCard: boolean = false; - private observers: Observer[] = []; - - constructor() { - try { - this.addSimChangeListener(); - this.getSimCardState(); - } catch (error) { - HiLog.w(TAG, "SimCardState, get sim state error.") - } - } - - /** - * attachObserver The subscription management methods. - * - * @param Observer the Observer need attach - */ - public attachObserver(observer: Observer): void { - const isExist = this.observers.includes(observer); - if (isExist) { - return console.log('Subject: Observer has been attached already.'); - } - HiLog.d(TAG, 'Subject: Attached an observer.'); - this.observers.push(observer); - if (observer) { - observer(); - } - } - - /** - * detachObserver - * - * @param Observer the Observer need detach - */ - public detachObserver(observer: Observer): void { - const observerIndex = this.observers.indexOf(observer); - if (observerIndex === -1) { - return console.log('Subject: Nonexistent observer.'); - } - - this.observers.splice(observerIndex, 1); - HiLog.d(TAG, 'Subject: Detached an observer.'); - } - - /** - * isSimReady - * - * @param slotId the sim slot id number - * @return boolean the sim is ready or not - */ - public isSimReady(slotId: number) { - return this.mSimStateArray[slotId] == telephonySim.SimState.SIM_STATE_READY || this.mSimStateArray[slotId] - == telephonySim.SimState.SIM_STATE_LOADED; - } - - private notify(): void { - HiLog.d(TAG, 'sim state changed: Notifying observers...'); - for (const observer of this.observers) { - observer(); - } - } - - private addSimChangeListener() { - HiLog.i(TAG, 'addSimChangeListener start ! '); - for (let i = 0; i < telephonySim.getMaxSimCount(); i++) { - observer.on('simStateChange', { - slotId: i - }, value => { - let simState = value?.state; - HiLog.i(TAG, 'simStateChange for simId_ONE, SIM value: ' + simState); - this.parseSimCardStateForSlot(i, simState); - }); - } - } - - private getSimCardState() { - HiLog.i(TAG, '-----getSimCardState-----'); - for (let i = 0; i < telephonySim.getMaxSimCount(); i++) { - telephonySim.getSimState(i, (err, value) => { - if (err) { - HiLog.e(TAG, `getSimCardState, ${i} error: ${JSON.stringify(err.message)}`); - } else { - this.parseSimCardStateForSlot(i, value) - } - }); - } - } - - private parseSimCardStateForSlot(slotId: number, value) { - HiLog.i(TAG, 'parseSimCardStateForSlot, slotId: ' + slotId + ', SimCardState value: ' + value); - let changed: boolean = (value != this.mSimStateArray[slotId]); - if (!changed) { - return; - } - this.mSimStateArray[slotId] = value; - this.haveSimCard = this.isSimReady(simId_ONE) || this.isSimReady(simId_TWO); - this.haveMultiSimCard = this.isSimReady(simId_ONE) && this.isSimReady(simId_TWO); - HiLog.i(TAG, 'parseSimCardStateForSlot sim state changed, haveSimCard: ' + this.haveSimCard + - ', haveMultiSimCard: ' + this.haveMultiSimCard); - this.notify(); - } -} - -export const simCardState: SimCardState = new SimCardState(); - -/** - * getLastUsedSlotId - * - * @return the last sim id number used to dail - */ -export function getLastUsedSlotId(): Promise { - return new Promise(async (resolve) => { - const value = await SharedPreferencesUtils.getFromPreferences(KEY_LAST_ID, simId_NONE) - HiLog.i(TAG, "getLastUsedSlotId:" + value); - resolve(value) - }); -} - -/** - * setLastUsedSlotId - * - * @param simId the sim id number - */ -export function setLastUsedSlotId(simId: number) { - HiLog.i(TAG, "setLastUsedSlotId:" + simId) - SharedPreferencesUtils.getFromPreferences(KEY_LAST_ID, simId); -} - -/** - * getSimName - * - * @param simId the sim id number - * @return the sim name to show - */ -export function getSimName(simId: number): Promise { - return new Promise((resolveInner) => { - telephonySim.getSimSpn(simId, (error, data) => { - if (error || !data) { - HiLog.i(TAG, "getSimSpn error" + JSON.stringify(error)) - telephonySim.getSimOperatorNumeric(simId, (error, opNum) => { - if (error) { - HiLog.i(TAG, "getSimOperatorNumeric error" + JSON.stringify(error)) - } else { - HiLog.i(TAG, "getSimSpn error, opNum:" + opNum) - resolveInner(opNum); - } - }) - } else { - resolveInner(data); - } - }) - }) -} \ No newline at end of file