api9

stage模型

arkts语言

//用到的文档
//https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/arkts-page-custom-components-lifecycle-0000001524296665-V3
//https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/accesstoken-guidelines-0000001493744016-V3#ZH-CN_TOPIC_0000001574088333__stage%E6%A8%A1%E5%9E%8B-1
//https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/permission-list-0000001544464017-V3

import geoLocationManager from '@ohos.geoLocationManager'
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
//权限列表
const permissions: Array<Permissions> = ['ohos.permission.APPROXIMATELY_LOCATION','ohos.permission.LOCATION'];
@Component
@Entry

struct Dingwei{

  // 检测权限是否已经授权,如果未授权就弹出授权弹框
  reqPermissionsFromUser(permissions: Array<Permissions>): void {
    let context = getContext(this) as common.UIAbilityContext;
    let atManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    atManager.requestPermissionsFromUser(context, permissions).then((data) => {
      let grantStatus: Array<number> = data.authResults;
      let length: number = grantStatus.length;
      for (let i = 0; i < length; i++) {
        if (grantStatus[i] === 0) {
          // 用户授权,可以继续访问目标操作
        } else {
          // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
          return;
        }
      }
      // 授权成功
    }).catch((err) => {
      console.error(`requestPermissionsFromUser failed, code is ${err.code}, message is ${err.message}`);
    })
  }

  //组件即将出现时回调该接口,具体时机为在创建自定义组件的新实例后,在执行其build()函数之前执行。
  aboutToAppear(){
    this.reqPermissionsFromUser(permissions)
  }

  build(){
    Button(){
      Text("获取定位")
        .fontColor(Color.White)
        .padding(30)
        .fontSize(30)
        .width("100%")
        .textAlign(TextAlign.Center)
    }.type(ButtonType.Normal)
    .onClick(()=>{
      //获取定位信息的函数
      let requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
      try {
        geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
          console.log('current location: ' + JSON.stringify(result));
        })
          .catch((error) => {
            console.log('promise, getCurrentLocation: error=' + JSON.stringify(error));
          });
      } catch (err) {
        console.error("errCode:" + err.code + ",errMessage:" + err.message);
      }
    })
  }

}