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

边栏推荐
- MySQL根据表前缀批量修改、删除表
- opencv 红色区域在哪里?
- Winxp kernel driver debugging
- Mobile mall project operation
- 騰訊開源項目「應龍」成Apache頂級項目:前身長期服務微信支付,能hold住百萬億級數據流處理...
- 老叶的祝福
- On the self-cultivation of an excellent red team member
- 严重的PHP缺陷可导致QNAP NAS 设备遭RCE攻击
- Work assessment of Biopharmaceutics of Jilin University in March of the 22nd spring -00005
- js工具函数,自己封装一个节流函数
猜你喜欢
![[rust submission] review impl trail and dyn trail in rust](/img/bc/05b3e031659ce19d6f6e3887d70512.jpg)
[rust submission] review impl trail and dyn trail in rust

Disassembly of Weima prospectus: the electric competition has ended and the intelligent qualifying has just begun

opencv是开源的吗?

威马招股书拆解:电动竞争已结束,智能排位赛刚开始

2022-06-21-Flink-49(一. SQL手册)

Nacos practice record

zabbix的安装避坑指南

Redis related-02

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

严重的PHP缺陷可导致QNAP NAS 设备遭RCE攻击
随机推荐
[rust submission] review impl trail and dyn trail in rust
Jilin University 22 spring March "official document writing" assignment assessment-00034
Mstp+vrrp+ospf implements a three-tier architecture
How to raise key issues in the big talk club?
Mobile mall project operation
Tianshu night reading notes - 8.4 diskperf disassembly
How to play well in the PMP Exam?
Randla net: efficient semantic segmentation of large scale point clouds
Teach you how to install win11 system in winpe
Internet Explorer died, and netizens started to build a true tombstone
Do you really need automated testing?
About sizeof() and strlen in array
ASP. Net conference room booking applet source code booking applet source code
论一个优秀红队人员的自我修养
Work assessment of Biopharmaceutics of Jilin University in March of the 22nd spring -00005
opencv是开源的吗?
MySQL根据表前缀批量修改、删除表
孙武玩《魔兽》?有图有真相
zabbix的安装避坑指南
BSC parsing input data of transaction