鸿蒙桌面快捷方式开发

发布于:2025-05-28 ⋅ 阅读:(38) ⋅ 点赞:(0)

桌面快捷方式开发实战

[参考文档] (https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-desktop-shortcuts)

在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信息的资源位置
          }
        ]
      }
    ]
  }
}

shortcuts_config.json文件

{
  "shortcuts": [
    {
      "shortcutId": "shortcutId1",
      "label": "$string:label1",
      "icon": "$media:icon1",
      "wants": [
        {
          "bundleName": "com.xxx.xxxx",
          "moduleName": "entry",
          "abilityName": "EntryAbility",
          "parameters": {
            "shortcutsNamePath": "parameters"
          }
        }
      ]
    }
  ]
}

在EntryAbility.ets接受参数

  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    if(want.parameters?.shortcutsNamePath){
      AppStorage.setOrCreate('shortcutsNamePath', want.parameters.shortcutsNamePath||'')
    }
...
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    if(want.parameters?.shortcutsNamePath){
      AppStorage.setOrCreate('shortcutsNamePath', want.parameters.shortcutsNamePath||'')
    }

使用HMRouter或者Navigation渲染完毕后恢复页面

  onPageShow(): void {
 // 根据存入的AppStorage书写恢复逻辑
  restoreThePageShortcut()
  }

恢复页面-快捷方式大概逻辑

export const restoreThePageShortcut = () => {
  const shortcutsNamePath = AppStorage.get('shortcutsNamePath') as string
  // 根据参数判断
if(shortcutsNamePath){
setTimeout(() => {
// 看情况处理
            AppStorage.setOrCreate('shortcutsNamePath', '') // 用完销毁
    })
}


}

注意,关于图片,最好使用1024*1024图片,中间的图标较小的

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述