通过geoLocationManager.on('locationEnabledChange')接口订阅“位置”配置的开关状态,在“设置-隐私和安全-位置-访问我的位置”或者手机右上角下拉的“位置”配置发生变化时,可以实时监听到变化并返回开关状态。
完整示例参考如下:
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);
}
}