目录

如何监听/获取“位置”配置的开关状态

问题现象

应用使用位置服务时,需要判断用户是否开启了“位置”配置,进一步实现相关业务,如何监听和获取“位置”配置的开关状态?

效果预览

背景知识

解决方案

完整示例参考如下:

import { geoLocationManager } from '@kit.LocationKit';

@Entry
@Component
struct CheckLocationEnable {
  @State getLocationEnableState: string = '未知';
  @State monitorEnableState: string = '未知';

  async aboutToAppear() {
    let locationEnabledChange = (state: boolean): void => {
      if (state) {
        this.monitorEnableState = '开';
      } else {
        this.monitorEnableState = '关';
      }
      console.info('locationEnabledChange: ' + JSON.stringify(state));
    };
    try {
      geoLocationManager.on('locationEnabledChange', locationEnabledChange);
    } catch (err) {
      console.error('errCode:' + err.code + ', message:' + err.message);
    }
  }

  build() {
    Column({ space: 20 }) {
      Button('获取当前位置开关状态')
        .onClick(() => {
          try {
            let locationEnabled = geoLocationManager.isLocationEnabled();
            if (locationEnabled) {
              this.getLocationEnableState = '开';
            } else {
              this.getLocationEnableState = '关';
            }
          } catch (err) {
            console.error('errCode:' + err.code + ', message:' + err.message);
          }
        });
      Text(`获取的位置开关状态为: ${this.getLocationEnableState}`);
      Text(`监听的位置开关状态为: ${this.monitorEnableState}`);
    }
    .height('100%')
    .width('100%')
    .padding(20);
  }
}