前言

静态快捷方式是一种在系统中创建的可以快速访问应用程序或特定功能的链接

快捷方式和它的名字一样,提供了一些快捷的功能入口,可以减少操作的深度。我们不用一步步的进入一二三级页面,而是直达目标页

file

鸿蒙中的快捷方式是静态的,配置相对简单。快捷菜单中的每一项还可以长按拖拽到桌面,这进一步减少了操作步骤,我们可以直接点击桌面上的快捷方式直达入口,甚至不用长按显示出快捷菜单后再选择功能然后进入

file

步骤

  1. 在/resources/base/profile/目录下创建名为shortcuts_config.json的文件,并在文件中定义应用快捷方式的相关配置。
{
  "shortcuts": [
    {
      "shortcutId": "id_company",
      "label": "$string:Go_to_the_Company",
      "icon": "$media:company",
      "wants": [
        {
          "bundleName": "com.example.desktopshortcuts",
          "moduleName": "entry",
          "abilityName": "EntryAbility",
          "parameters": {
            "shortCutKey": "CompanyPage"
          }
        }
      ]
    },
    {
      "shortcutId": "id_house",
      "label": "$string:Go_to_House",
      "icon": "$media:house",
      "wants": [
        {
          "bundleName": "com.example.desktopshortcuts",
          "moduleName": "entry",
          "abilityName": "EntryAbility",
          "parameters": {
            "shortCutKey": "HousePage"
          }
        }
      ]
    }
  ]
}
  1. 在module.json5配置文件中的abilities标签下的metadata中设置resource属性值为$profile:shortcuts_config,指定应用的快捷方式配置文件,即使用shortcuts_config.json文件中的shortcuts配置
{
  "module": {
    // ...
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        // ...
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "ohos.want.action.home"
            ]
          }
        ],
        "metadata": [
          {
            "name": "ohos.ability.shortcuts", // 配置快捷方式,该值固定为ohos.ability.shortcuts
            "resource": "$profile:shortcuts_config" // 指定shortcuts信息的资源位置
          }
        ]
      }
    ]
  }
}
  1. 在EntryAbility.ets文件中的onNewWant()/onCreate()函数中,通过获取want中的parameters里的shortCutKey来判断用户使用了哪种快捷方式(可以将跳转方法抽离出一个公共方法,将want传入。在onCreate/onNewWant中调用)
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
  this.goToSpecifyPage(want);
}

onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  this.goToSpecifyPage(want);
}

goToSpecifyPage(want: Want) {
  let shortCutKey = want.parameters?.shortCutKey;

  if (this.uiContext && shortCutKey && shortCutKey === 'CompanyPage') {
    let router: Router = this.uiContext.getRouter();
    router.pushUrl({
      url: 'pages/GoCompany'
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', `Failed to push url. Code is ${err.code},message is ${err.message}`);
    });
  }
}

参考资料

  1. 桌面快捷方式开发实践
  2. 创建应用静态快捷方式
  3. shortcuts标签
  4. 快捷方式示例工程

欢迎关注我(unravel2025),感谢您的阅读