当前位置:网站首页>[harmony OS] [ark UI] basic ETS context operations
[harmony OS] [ark UI] basic ETS context operations
2022-06-25 03:57:00 【Huawei Developer Forum】
stay HarmonyOS In development ,‘ Permission to apply for ’,‘ Permission check ’,‘ Get version information ’,‘ Get package name ’ It's all basic operations , Today, learn how to implement the following functions , It is mainly divided into ‘Api explain ’,‘ Code implementation ’,‘ Running effect ’ Three steps are described
1. Api explain
1.1 Reference resources Ability Context
1.2 context.verifyPermission
verifyPermission(permission: string, options?: PermissionOptions): Promise
Check whether the specified process has the specified permission ,options Is an optional parameter , If it is not set, it means to check its own permissions , Use Promise As an asynchronous method .
1.2.1 Request parameters
Parameter one permission: Permissions requiring verification
Parameter two options: contain pid,uid( Conventional applications do not use , There is no detailed explanation here )
1.2.2 Return type
Promise:Promise Return the result in the form of . return -1 Indicates that you do not have the current check permission ,0 It means you have permission
1.2.3 Example :
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
Request certain permissions from the user , Before applying for permission, query whether its own process has been granted the permission (verifyPermission), If you already have permission , There is no need to apply for , Otherwise, you need to apply for permission . Use Promise As an asynchronous method .
1.3.1 Parameters,
Parameter one :permissions: Request permission granted
Shen II :requestCode : Request status code The specific request code corresponding to the matching application , Value range : Greater than or equal to 0
1.3.2 Return value :Promise: Callback function , You can process the interface return value in the callback function , Return the permission request result
1.3.3PermissionRequestResult Properties,
requestCode: Get the returned request code , It is mainly used to determine which permission is requested
permissions: Request permission collection
authResults: Permission verification results , return -1 Indicates that you do not have the current check permission ,0 It means you have permission
1.3.4 Example
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
Get the version information of the application , Use Promise As an asynchronous method .
1.4.2 Return results :Promise: Return the application version information .
AppVersionInfo Parameters,
appName: apply name
versionCode: Application version number
versionName: Application version name
1.4.3 The preparation of information needs to be done in config.json Search for version label , As shown in the figure below

1.4.4 Sample code
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
obtain Ability The package name information of the , Use Promise As an asynchronous method .
Return value :Promise:Promise returns Ability The package name information of the .
1.5.2 Reference resources The elements of the configuration file Of bundleName. The effect is as follows

2. Code implementation
2.1 Need to be in config.json Registration rights , Reference resources The elements of the configuration file Of reqPermissions

2.2 At present, the application authority is as follows
2.2.1 ohos.permission.READ_USER_STORAGE
2.2.2 ohos.permission.CAMERA

2.2.3 All the code
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(' Currently do not have permission ' ); }else{ console.log(' Currently, you have permission ' ); } }).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(" Request code "+data.requestCode) console.log(" Request permission "+data.permissions.toString()) if(requestCode===data.requestCode){// It is used to judge whether the returned request code is the same as the applied request for(var i=0;i<data.permissions.length;i++){ if(data.authResults[i]==-1){ console.log(" Request permission :"+data.permissions[i]+"==> The request status is rejected ") }else{ console.log(" Request permission :"+data.permissions[i]+"==> The request status is consent ") } } } }).catch((error) => { console.log('Operation failed. Cause: ' + JSON.stringify(error)); }) } private MyGetAppVersionInfo() { var context = ability_featureAbility.getContext(); context.getAppVersionInfo() .then((data) => { console.log("getAppVersionInfo===> apply name :"+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 Package name : ' + 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(' Check current permissions ') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.myVerifyPermission.bind(this)) Text(' Application authority ') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.MyRequestPermissionsFromUser.bind(this)) .backgroundColor(Color.Red) Text(' Get version information ') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.MyGetAppVersionInfo.bind(this)) Text(' Get package name ') .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(this.myGetBundleName.bind(this)) .backgroundColor(Color.Red) } .width('100%') .height('100%') }}3. Running effect

边栏推荐
- Mstp+vrrp+ospf implements a three-tier architecture
- redis
- 后台页制作01《ivx低代码签到系统制作》
- 扎克伯格最新VR原型机来了,要让人混淆虚拟与现实的那种
- JS tool function, self encapsulating a throttling function
- The programmer reality show is coming again! Hulan, as the host, carried the lamp to fill the knowledge. The SSS boss had a bachelor's degree in pharmacy. Zhu Jun and Zhang Min from Tsinghua joined th
- 存算一体芯片离普及还有多远?听听从业者怎么说 | 对撞派 x 后摩智能
- Oracle-sqlload import external data details
- AI自己写代码让智能体进化!OpenAI的大模型有“人类思想”那味了
- 【Harmony OS】【ArkUI】ets开发 图形与动画绘制
猜你喜欢

The programmer reality show is coming again! Hulan, as the host, carried the lamp to fill the knowledge. The SSS boss had a bachelor's degree in pharmacy. Zhu Jun and Zhang Min from Tsinghua joined th

9 necessary soft skills for program ape career development

西电AI专业排名超清北,南大蝉联全国第一 | 2022软科中国大学专业排名

Musk was sued for $258billion in MLM claims. TSMC announced the 2nm process. The Chinese Academy of Sciences found that the lunar soil contained water in the form of hydroxyl. Today, more big news is

Crawler grabs the data of Douban group

Perfect shuffle problem

How to use crawlers to capture bullet screen and comment data of station B?

How to play well in the PMP Exam?

Apple's legendary design team disbanded after jobs refused to obey cook

How far is the memory computing integrated chip from popularization? Listen to what practitioners say | collision school x post friction intelligence
随机推荐
MySQL根据表前缀批量修改、删除表
后台页制作01《ivx低代码签到系统制作》
Sun Wu plays Warcraft? There is a picture and a truth
论一个优秀红队人员的自我修养
How to raise key issues in the big talk club?
马斯克被诉传销索赔2580亿美元,台积电公布2nm制程,中科院发现月壤中含有羟基形式的水,今日更多大新闻在此...
【Harmony OS】【ARK UI】ETS 上下文基本操作
opencv最大能打开多少图像?
ASP.NET会议室预约小程序源码 预约小程序源码
2022-06-21-Flink-49(一. SQL手册)
zabbix的安装避坑指南
Jilin University 22 spring March "official document writing" assignment assessment-00029
Comprehensive assignment of thesis writing instruction of Dongcai
Oracle-sqlload import external data details
佐喃社区
AI越进化越跟人类大脑像!Meta找到了机器的“前额叶皮层”,AI学者和神经科学家都惊了...
Understand (DI) dependency injection in PHP
【Rust投稿】从零实现消息中间件(6)-CLIENT
(超详细onenet TCP协议接入)arduino+esp8266-01s接入物联网平台,上传实时采集数据/TCP透传(以及lua脚本如何获取和编写
Background page production 01 production of IVX low code sign in system