目录

如何获取APP的系统名称与桌面名称

问题现象

开发者在开发过程中,需要获取APP的名称用于一些功能展示,如何获取APP的名称呢?

背景知识

APP名称可以分为系统APP名称与桌面APP名称。

解决方案

获取APP的系统名称与桌面名称有两种方案:

import common from '@ohos.app.ability.common';
import { bundleManager } from '@kit.AbilityKit';

@Entry
@Component
struct Index1 {
  @State systemAPPNameOne: string = '';
  @State systemAPPNameTwo: string = '';
  @State desktopAppNameOne: string = '';
  @State desktopAppNameTwo: string = '';

  aboutToAppear(): void {
    const context = this.getUIContext().getHostContext() as common.UIAbilityContext;
    // 获取系统APP的名称
    let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
    let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags);
    let appLabel: string = bundleInfo.appInfo.label;
    let appRes = appLabel.split(':')[1];
    this.systemAPPNameOne = context.resourceManager.getStringByNameSync(appRes);
    console.info('方案一:获取系统APP的名称:', this.systemAPPNameOne);
    this.systemAPPNameTwo = context.resourceManager.getStringSync($r('app.string.app_name').id);
    console.info('方案二:获取系统APP的名称:', this.systemAPPNameTwo);
    // 获取桌面APP的名称
    let windowAppLabel = context.abilityInfo.label;
    let windowAppRes = windowAppLabel.split(':')[1];
    this.desktopAppNameOne = context.resourceManager.getStringByNameSync(windowAppRes);
    console.info('方案一:获取桌面APP的名称:', this.desktopAppNameOne);
    this.desktopAppNameTwo = context.resourceManager.getStringSync($r('app.string.EntryAbility_label').id);
    console.info('方案二:获取桌面APP的名称:', this.desktopAppNameTwo);
  }

  build() {
    Row() {
      Column() {
        Text('方案一:系统APP的名称: ' + this.systemAPPNameOne)
          .fontSize(20);
        Text('方案二:系统APP的名称: ' + this.systemAPPNameTwo)
          .fontSize(20);
        Text('方案一:桌面APP的名称: ' + this.desktopAppNameOne)
          .fontSize(20);
        Text('方案二:桌面APP的名称: ' + this.desktopAppNameTwo)
          .fontSize(20);
      }
      .width('100%');
    }
    .height('100%');
  }
}

验证图示和桌面APP图示如下:

常见FAQ

Q:在module.json5中修改了label属性,但是APP名称显示未生效?

A:建议卸载APP重新安装。