当前位置:网站首页>[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

边栏推荐
- Sun Wu plays Warcraft? There is a picture and a truth
- [rust contribution] implement Message Oriented Middleware (6) -client from zero
- Perfect shuffle problem
- 【Rust投稿】捋捋 Rust 中的 impl Trait 和 dyn Trait
- 太极图形60行代码实现经典论文,0.7秒搞定泊松盘采样,比Numpy实现快100倍
- 9 necessary soft skills for program ape career development
- Xidian AI ranked higher than Qingbei in terms of AI majors, and Nantah ranked the first in China in 2022 in terms of soft science majors
- Apple's legendary design team disbanded after jobs refused to obey cook
- 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
- 华为上诉失败,被禁止在瑞典销售 5G 设备;苹果公司市值重获全球第一;Deno 完成 2100 万美元 A 轮融资|极客头条
猜你喜欢

IE寿终正寝,网友们搞起了真·墓碑……

Nacos practice record

马斯克:推特要学习微信,让10亿人「活在上面」成为超级APP

ICML 2022 | 字节跳动 AI Lab 提出多模态模型:X-VLM,学习视觉和语言的多粒度对齐...

存算一体芯片离普及还有多远?听听从业者怎么说 | 对撞派 x 后摩智能

【组队学习】SQL编程语言笔记——Task04

墨天轮访谈 | IvorySQL王志斌—IvorySQL,一个基于PostgreSQL的兼容Oracle的开源数据库

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

MySQL modifies and deletes tables in batches according to the table prefix

Peking University has a new president! Gongqihuang, academician of the Chinese Academy of Sciences, took over and was admitted to the Physics Department of Peking University at the age of 15
随机推荐
Understand (DI) dependency injection in PHP
Work assessment of Biopharmaceutics of Jilin University in March of the 22nd spring -00005
Comprehensive operation of financial risk management X of Dongcai
吴恩达机器学习新课程又来了!旁听免费,小白友好
X86 CPU, critical! The latest vulnerability has caused heated discussion. Hackers can remotely steal keys. Intel "all processors" are affected
Jilin University 22 spring March "official document writing" assignment assessment-00084
Xidian AI ranked higher than Qingbei in terms of AI majors, and Nantah ranked the first in China in 2022 in terms of soft science majors
Crawler crawls Sina Weibo data
x86 CPU,危!最新漏洞引发热议,黑客可远程窃取密钥,英特尔“全部处理器”受影响...
腾讯开源项目「应龙」成Apache顶级项目:前身长期服务微信支付,能hold住百万亿级数据流处理...
OpenSUSE environment PHP connection Oracle
PHP uses getid3 to obtain the duration of MP3, MP4, WAV and other media files
Self cultivation and learning encouragement
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
How to use crawlers to capture bullet screen and comment data of station B?
多睡觉,能减肥,芝加哥大学最新研究:每天多睡1小时,等于少吃一根炸鸡腿...
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
2点睡10点起不算熬夜?除非你每天都能执行
Lao Ye's blessing
亚马逊在中国的另一面