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