1/* 2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import geolocation from '@ohos.geoLocationManager'; 17import Log from '../../../../../../../../common/src/main/ets/default/Log'; 18import createOrGet from '../../../../../../../../common/src/main/ets/default/SingleInstanceHelper'; 19 20const TAG = 'LocationModel'; 21 22export interface LocationStatrListener { 23 updateServiceState(status: boolean): void; 24} 25 26export class LocationService { 27 mIsStart = false; 28 mListener: LocationStatrListener; 29 30 startService(): void { 31 if (this.mIsStart) { 32 return; 33 } 34 Log.showInfo(TAG, 'startService'); 35 this.mIsStart = true; 36 this.getServiceState(); 37 geolocation.on('locationEnabledChange', (state: boolean) => { 38 Log.showInfo(TAG, `startService locationChange, state: ${JSON.stringify(state)}`); 39 this.getServiceState(); 40 }); 41 } 42 43 stopService(): void { 44 if (!this.mIsStart) { 45 return; 46 }; 47 Log.showInfo(TAG, 'stopService'); 48 this.mIsStart = false; 49 geolocation.off('locationEnabledChange', (state: boolean) => { 50 Log.showInfo(TAG, `stopService locationChange, state: ${JSON.stringify(state)}`) 51 }); 52 } 53 54 registerListener(listener: LocationStatrListener): void { 55 Log.showInfo(TAG, `registerListener, listener: ${listener}`); 56 this.mListener = listener; 57 } 58 59 getServiceState(): void { 60 Log.showDebug(TAG, 'getServiceState'); 61 let data = geolocation.isLocationEnabled() 62 Log.showInfo(TAG, `getServiceState isLocationEnabled, data: ${JSON.stringify(data)}`); 63 this.mListener?.updateServiceState(data); 64 } 65 66 enableLocation(): void { 67 Log.showInfo(TAG, 'enableLocation'); 68 geolocation.enableLocation() 69 .then((res) => Log.showInfo(TAG, `enableLocation, result: ${JSON.stringify(res)}`)) 70 .then(() => { 71 }).catch((err) => { 72 }); 73 } 74 75 disableLocation(): void { 76 Log.showInfo(TAG, 'disableLocation'); 77 geolocation.disableLocation() 78 } 79} 80 81let sLocationService = createOrGet(LocationService, TAG); 82 83export default sLocationService;