当前位置:网站首页>【Harmony OS】【ARK UI】ETS 上下文基本操作
【Harmony OS】【ARK UI】ETS 上下文基本操作
2022-06-25 03:42:00 【华为开发者论坛】
在HarmonyOS开发中,‘权限申请’,‘权限检查’,‘获取版本信息’,‘获取包名’都是基本操作,今天学习一下怎么实现如下功能,主要分为‘Api说明’,‘代码实现’,‘运行效果’三个步骤进行描述
1. Api说明
1.1参考Ability上下文
1.2 context.verifyPermission
verifyPermission(permission: string, options?: PermissionOptions): Promise
检查指定进程是否存在指定的权限,options为可选参数,不设置时表示检查自身权限,使用Promise方式作为异步方法。
1.2.1请求参数
参数一permission:需要校验的权限
参数二options:包含pid,uid(常规应用使用不到,这里不做详细讲解)
1.2.2 返回类型
Promise:Promise形式返回结果。返回-1表示不具备当前检查权限,0表示有权限
1.2.3示例:
import ability_featureAbility from '@ohos.ability.featureAbility'var context = ability_featureAbility.getContext();let permission = "ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS";context.verifyPermission(permission,(error, data)=>{ if (error) { console.error('Operation failed. Cause: ' + JSON.stringify(error)); return; } console.info('Operation successful. Data:' + JSON.stringify(data))})
1.3 context.requestPermissionsFromUser
requestPermissionsFromUser(permissions: Array, requestCode: number): Promise
向用户请求某些权限,在申请权限之前查询自身进程是否已被授予该权限(verifyPermission),如果已有权限,则无需申请,否则需要申请权限。使用Promise方式作为异步方法。
1.3.1参数详解
参数一:permissions:请求授予的权限
参二:requestCode :请求状态码 与匹配应用程序对应的特定请求代码,取值范围:大于等于0
1.3.2返回值:Promise:回调函数,可以在回调函数中处理接口返回值,返回权限请求结果
1.3.3PermissionRequestResult属性详解
requestCode:得到返回的请求码,主要作用用于判断是哪个请求的权限的作用
permissions:请求权限集合
authResults:权限验证结果,返回-1表示不具备当前检查权限,0表示有权限
1.3.4示例
import ability_featureAbility from '@ohos.ability.featureAbility'var context = ability_featureAbility.getContext();let permissions = ["ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS","ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION"];let requestCode = 123context.requestPermissionsFromUser(permissions, requestCode) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data));}).catch((error) => { console.error('Operation failed. Cause: ' + JSON.stringify(error));})
1.4.1 context.getAppVersionInfo
getAppVersionInfo():Promise
获取应用的版本信息,使用Promise方式作为异步方法。
1.4.2返回结果:Promise:返回应用版本信息。
AppVersionInfo参数详解
appName:应用名称
versionCode:应用版本号
versionName:应用版本名称
1.4.3准备资料需要在config.json中查找version标签,如下图所示
1.4.4 示例代码
import ability_featureAbility from '@ohos.ability.featureAbility'var context = ability_featureAbility.getContext();context.getAppVersionInfo() .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data));}).catch((error) => { console.error('Operation failed. Cause: ' + JSON.stringify(error));})
1.5.1 context.getBundleName
getBundleName(): Promise
获取Ability的所属的包名信息,使用Promise方式作为异步方法。
返回值:Promise:Promise形式返回Ability的所属的包名信息。
1.5.2参考配置文件的元素的bundleName。效果如如下
2. 代码实现
2.1需要在config.json 注册权限,参考配置文件的元素的reqPermissions
2.2目前申请权限如下
2.2.1 ohos.permission.READ_USER_STORAGE
2.2.2 ohos.permission.CAMERA
2.2.3 全部代码
import ability_featureAbility from '@ohos.ability.featureAbility'@[email protected] MyFeatureAbilityPage { private myVerifyPermission() { var context = ability_featureAbility.getContext(); let permission = "ohos.permission.CAMERA"; context.verifyPermission(permission, null) .then((data) => { if(data===-1){ console.log('当前没有权限 ' ); }else{ console.log('当前已具备权限 ' ); } }).catch((error) => { console.log('Operation failed. Cause: ' + JSON.stringify(error)); }) } private MyRequestPermissionsFromUser() { var context = ability_featureAbility.getContext(); let permissions = ["ohos.permission.CAMERA","ohos.permission.READ_USER_STORAGE"]; let requestCode = 123 context.requestPermissionsFromUser(permissions, requestCode) .then((data) => { console.log("请求码"+data.requestCode) console.log("请求权限"+data.permissions.toString()) if(requestCode===data.requestCode){//用于判断返回的请求码和申请的请求是否相同 for(var i=0;i<data.permissions.length;i++){ if(data.authResults[i]==-1){ console.log("请求权限:"+data.permissions[i]+"==>请求状态是拒绝") }else{ console.log("请求权限:"+data.permissions[i]+"==>请求状态是同意") } } } }).catch((error) => { console.log('Operation failed. Cause: ' + JSON.stringify(error)); }) } private MyGetAppVersionInfo() { var context = ability_featureAbility.getContext(); context.getAppVersionInfo() .then((data) => { console.log("getAppVersionInfo===>应用名称:"+data.appName) console.log("getAppVersionInfo===>versionCode:"+data.versionCode) console.log("getAppVersionInfo===>versionName:"+data.versionName) }).catch((error) => { console.log('Operation failed. Cause: ' + JSON.stringify(error)); }) } private myGetBundleName() { var context = ability_featureAbility.getContext(); context.getBundleName() .then((data) => { console.log('getBundleName包名: ' + JSON.stringify(data)); }).catch((error) => { console.log('Operation failed. Cause: ' + JSON.stringify(error)); }) } build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Text('检查当前权限') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.myVerifyPermission.bind(this)) Text('申请权限') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.MyRequestPermissionsFromUser.bind(this)) .backgroundColor(Color.Red) Text('获取版本信息') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.MyGetAppVersionInfo.bind(this)) Text('获取包名') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.myGetBundleName.bind(this)) .backgroundColor(Color.Red) } .width('100%') .height('100%') }}
3. 运行效果
边栏推荐
- Winxp kernel driver debugging
- MySQL根据表前缀批量修改、删除表
- 股票在网上开户安全吗?在线等答案
- Tencent Open Source Project "Yinglong" est devenu un projet Apache de haut niveau: l'ancien Service à long terme Wechat payment, peut maintenir un million de milliards de niveaux de traitement de flux
- What if Alipay is controlled by risk for 7 days? Payment solution
- How to choose a securities company when opening an account with a compass? Which is safer
- Solution to the problem that Linux crontab timed operation Oracle does not execute (crontab environment variable problem)
- js工具函数,自己封装一个节流函数
- Now, the ear is going into the metauniverse
- Standing at the center of the storm: how to change the engine of Tencent
猜你喜欢
Does it count as staying up late to sleep at 2:00 and get up at 10:00? Unless you can do it every day
Apple's legendary design team disbanded after jobs refused to obey cook
Break the memory wall with CPU scheme? Learn from PayPal stack to expand capacity, and the volume of missed fraud transactions can be reduced to 1/30
存算一体芯片离普及还有多远?听听从业者怎么说 | 对撞派 x 后摩智能
About PLSQL error initialization failure
JSP cannot be resolved to a type error reporting solution
騰訊開源項目「應龍」成Apache頂級項目:前身長期服務微信支付,能hold住百萬億級數據流處理...
马斯克:推特要学习微信,让10亿人「活在上面」成为超级APP
陆奇首次出手投资量子计算
The era of copilot free is over! The official version is 67 yuan / month, and the student party and the defenders of popular open source projects can prostitute for nothing
随机推荐
CVPR大会现场纪念孙剑博士,最佳学生论文授予同济阿里,李飞飞获黄煦涛纪念奖...
浏览器下载的文件属性里都有保护,如何去掉
The more AI evolves, the more it resembles the human brain! Meta found the "prefrontal cortex" of the machine. AI scholars and neuroscientists were surprised
Is it safe to open an account on the compass? Is it reliable?
Wuenda, the new course of machine learning is coming again! Free auditing, Xiaobai friendly
马斯克被诉传销索赔2580亿美元,台积电公布2nm制程,中科院发现月壤中含有羟基形式的水,今日更多大新闻在此...
你真的需要自动化测试吗?
Redis related-01
程序猿职业发展9项必备软技能
MySQL modifies and deletes tables in batches according to the table prefix
【Rust投稿】捋捋 Rust 中的 impl Trait 和 dyn Trait
华为上诉失败,被禁止在瑞典销售 5G 设备;苹果公司市值重获全球第一;Deno 完成 2100 万美元 A 轮融资|极客头条
Eggservice builds the basic service of wechat official account
C语言数组与结构体指针
Background page production 01 production of IVX low code sign in system
Program. Launch (xxx) open file
Does it count as staying up late to sleep at 2:00 and get up at 10:00? Unless you can do it every day
OpenSUSE installation pit log
网上开户股票安全吗?怎么开户呢?
China's SkyEye found suspicious signals of extraterrestrial civilization. Musk said that the Starship began its orbital test flight in July. Netinfo office: app should not force users to agree to proc