• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static instance: GeoLocation
23  private TAG: string = '[GeoLocation]:'
24  private requestInfo: geolocation.LocationRequest = {
25    priority: 0x203,
26    scenario: 0x300,
27    timeInterval: 0,
28    distanceInterval: 0,
29    maxAccuracy: 0
30  }
31
32  public static getInstance() {
33    if (!GeoLocation.instance) {
34      GeoLocation.instance = new GeoLocation()
35    }
36    return GeoLocation.instance
37  }
38
39  public async on() {
40    Log.info(`${this.TAG} on E`)
41    if (!SettingManager.getInstance().getSaveGeoLocation()) {
42      Log.info(`${this.TAG} on geo setting off, X`)
43      return
44    }
45    geolocation.isLocationEnabled().then((result) => {
46      Log.info(`${this.TAG} isLocationEnabled: ${result}`)
47      if (result) {
48        let curRequestInfo: geolocation.CurrentLocationRequest = {
49          'priority': 0x203,
50          'scenario': 0x300,
51          'maxAccuracy': 1000
52        }
53        geolocation.getCurrentLocation(curRequestInfo).then((result) => {
54          Log.info(`${this.TAG} on getCurrentLocation result: ${JSON.stringify(result)}`)
55          SettingManager.getInstance().setCurGeoLocation(result)
56        }).catch((err: BusinessError) => {
57          Log.info(`${this.TAG} on getCurrentLocation err result: ${JSON.stringify(err)}`)
58        })
59        geolocation.on('locationChange', this.requestInfo, this.locationChange)
60      }
61    })
62    Log.info(`${this.TAG} on X`)
63  }
64
65  public async off() {
66    Log.info(`${this.TAG} off E`)
67    if (!SettingManager.getInstance().getSaveGeoLocation()) {
68      Log.info(`${this.TAG} off geo setting off X`)
69      return
70    }
71    geolocation.off('locationChange', this.locationChange)
72    Log.info(`${this.TAG} off X`)
73  }
74
75  private locationChange = (location: geolocation.Location): void => { //删掉参数err及相关逻辑
76    Log.info(`[GeoLocation]: locationChange: ${location}`)
77    SettingManager.getInstance().setCurGeoLocation(location)
78  }
79}