1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import geolocation from '@ohos.geolocation'; 17import { Log } from '../../utils/Log'; 18import { SettingManager } from '../../setting/SettingManager'; 19import { BusinessError } from '@ohos.base'; 20 21export class GeoLocation { 22 private TAG: string = '[GeoLocation]:' 23 private static instance: GeoLocation 24 private requestInfo: geolocation.LocationRequest = { 25 priority: 0x203, 26 scenario: 0x300, 27 timeInterval: 0, 28 distanceInterval: 0, 29 maxAccuracy: 0 30 } 31 private locationChange = (location: geolocation.Location): void => { //删掉参数err及相关逻辑 32 Log.info(`[GeoLocation]: locationChange: ${location}`) 33 SettingManager.getInstance().setCurGeoLocation(location) 34 } 35 36 public static getInstance() { 37 if (!GeoLocation.instance) { 38 GeoLocation.instance = new GeoLocation() 39 } 40 return GeoLocation.instance 41 } 42 43 public async on() { 44 Log.info(`${this.TAG} on E`) 45 if (!SettingManager.getInstance().getSaveGeoLocation()) { 46 Log.info(`${this.TAG} on geo setting off, X`) 47 return 48 } 49 geolocation.isLocationEnabled().then((result) => { 50 Log.info(`${this.TAG} isLocationEnabled: ${result}`) 51 if (result) { 52 let curRequestInfo: geolocation.CurrentLocationRequest = { 53 'priority': 0x203, 54 'scenario': 0x300, 55 'maxAccuracy': 1000 56 } 57 geolocation.getCurrentLocation(curRequestInfo).then((result) => { 58 Log.info(`${this.TAG} on getCurrentLocation result: ${JSON.stringify(result)}`) 59 SettingManager.getInstance().setCurGeoLocation(result) 60 }).catch((err:BusinessError) => { 61 Log.info(`${this.TAG} on getCurrentLocation err result: ${JSON.stringify(err)}`) 62 }) 63 geolocation.on('locationChange', this.requestInfo, this.locationChange) 64 } 65 }) 66 Log.info(`${this.TAG} on X`) 67 } 68 69 public async off() { 70 Log.info(`${this.TAG} off E`) 71 if (!SettingManager.getInstance().getSaveGeoLocation()) { 72 Log.info(`${this.TAG} off geo setting off X`) 73 return 74 } 75 geolocation.off('locationChange', this.locationChange) 76 Log.info(`${this.TAG} off X`) 77 } 78}