当前位置:网站首页>[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
边栏推荐
- Teach you how to install win11 system in winpe
- Dr. Sun Jian was commemorated at the CVPR conference. The best student thesis was awarded to Tongji Ali. Lifeifei won the huangxutao Memorial Award
- Redis related-01
- Work assessment of pharmacotherapeutics of Jilin University in March of the 22nd spring -00064
- ASP.NET会议室预约小程序源码 预约小程序源码
- About PLSQL error initialization failure
- Understand (DI) dependency injection in PHP
- 一文搞懂php中的(DI)依赖注入
- ICML 2022 | ByteDance AI Lab proposes a multimodal model: x-vlm, learning multi granularity alignment of vision and language
- 【Rust投稿】捋捋 Rust 中的 impl Trait 和 dyn Trait
猜你喜欢
Wuenda, the new course of machine learning is coming again! Free auditing, Xiaobai friendly
2点睡10点起不算熬夜?除非你每天都能执行
Redis related-03
Lao Ye's blessing
Background page production 01 production of IVX low code sign in system
吴恩达机器学习新课程又来了!旁听免费,小白友好
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
ZABBIX installation pit avoidance Guide
2022-06-21-Flink-49(一. SQL手册)
Time management understood after working at home | community essay solicitation
随机推荐
BGP biplane architecture
TC object structure and abbreviation
【Harmony OS】【ARK UI】ETS 上下文基本操作
2022-06-21-Flink-49(一. SQL手册)
你真的需要自动化测试吗?
程序员真人秀又来了!呼兰当主持挑灯狂补知识,SSS大佬本科竟是药学,清华朱军张敏等加入导师团...
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
Two common OEE monitoring methods for equipment utilization
windows 2003 64位系统php运行报错:1% 不是有效的 win32 应用程序
Comprehensive assignment of thesis writing instruction of Dongcai
How to use crawlers to capture bullet screen and comment data of station B?
Work assessment of Biopharmaceutics of Jilin University in March of the 22nd spring -00005
Jilin University 22 spring March "automatic control principle" work assessment-00050
Oracle-sqlload import external data details
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
9 necessary soft skills for program ape career development
Maybe it's the wrong reason
Dr. Sun Jian was commemorated at the CVPR conference. The best student thesis was awarded to Tongji Ali. Lifeifei won the huangxutao Memorial Award
Amazon's other side in China
Apple's legendary design team disbanded after jobs refused to obey cook