介绍
通过 ApplicationInfo 可以获取应用名、tokenID(accessTokenId,用于鉴权)等信息
步骤
应用程序信息,三方应用可以通过 bundleManager.getBundleInfoForSelf() 获取自身的应用程序信息,其中入参 bundleFlags 至少包含GET_BUNDLE_INFO_WITH_APPLICATION
1. 获取 BundleInfo
第三方应用,首先获取 BundleInfo
import { bundleManager } from '@kit.AbilityKit';
let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
解释: GET_BUNDLE_INFO_WITH_APPLICATION 详见链接
2. 通过 BundleInfo 获取 ApplicationInfo
let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
有坑
HarmonyOS NEXT鸿蒙开发:bundleManager.getBundleInfoForSelf() 坑-不要写在 onCreate() 方法中
例子
获取 tokenId
导入模块:
import { abilityAccessCtrl, common, Permissions,bundleManager } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
代码:
let tokenId: number = 0;
try {
let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
tokenId = appInfo.accessTokenId;
} catch (error) {
const err: BusinessError = error as BusinessError;
console.error(TAG,`获取 bundle info 失败! Code is ${err.code}, message is ${err.message}`);
}