一、前言
靜態快捷方式是一種在系統中創建的可以快速訪問應用程序或特定功能的鏈接。它通常可以在長按應用圖標,以圖標和相應的文字出現在應用圖標的上方,用戶可以迅速啟動對應應用程序的組件。使用快捷方式,可以提高效率,節省了查找和打開對應的組件時間;也可以實現個性化定制的需求,創建多個快捷方式,以滿足個性化的工作流程和操作偏好。應用配置靜態快捷方式,在桌面上展示的效果如下圖:
安裝該應用后,在桌面上長按該應用圖標,在應用的圖標上方會出現開發者配置的快捷方式(“創建應用靜態快捷方式詳情”和“分享好友”),點擊對應的標簽,即可拉起對應的組件。
二、shortcuts標簽
shortcuts標識應用的快捷方式信息。標簽值為數組,包含四個子標簽shortcutId、label、icon、wants。
metadata中指定shortcut信息,其中:
- name:指定shortcuts的名稱,使用ohos.ability.shortcuts作為shortcuts信息的標識。
- resource:指定shortcuts信息的資源位置。
shortcuts標簽說明
屬性名稱 | 含義 | 類型 | 是否可缺省 |
---|---|---|---|
shortcutId | 標識快捷方式的ID,取值為長度不超過63字節的字符串。不支持通過資源索引的方式($string)配置該字段。 | 字符串 | 該標簽不可缺省。 |
label | 標識快捷方式的標簽信息,即快捷方式對外顯示的文字描述信息。取值為長度不超過255字節的字符串,可以是描述性內容,也可以是標識label的資源索引。 | 字符串 | 該標簽可缺省,缺省值為空。 |
icon | 標識快捷方式的圖標,取值為資源文件的索引。 | 字符串 | 該標簽可缺省,缺省值為空。 |
wants | 標識快捷方式內定義的目標wants信息集合,在調用launcherBundleManager的startShortcut接口時,會拉起wants標簽里的第一個目標組件,推薦只配置一個wants元素。 | 對象 | 該標簽可缺省,缺省為空。 |
三、配置方法
2.1 配置快捷方式的配置文件。
開發者若要配置靜態快捷方式,可以在某個模塊的/resources/base/profile/目錄下配置快捷方式的配置文件,如shortcuts_config.json。
{"shortcuts": [{"shortcutId": "id_test1", // 標識快捷方式,在應用有多個快捷方式時,該字段可作為快捷方式的唯一標識符"label": "$string:share", // 標識該快捷方式對外顯示的文字"icon": "$media:share_icon", // 標識該快捷方式對外顯示的圖片"wants": [{"bundleName": "com.ohos.hello", // 對應該快捷方式對應拉起組件的包名"moduleName": "entry", // 對應該快捷方式對應拉起組件的模塊名"abilityName": "EntryAbility", // 對應該快捷方式對應拉起組件的組件名"parameters": {"testKey": "testValue" // 表示拉起快捷方式時的自定義數據}}]}]
}
示例圖
2.2 在應用module.json5文件中配置metadata指向快捷方式的配置文件。
在module.json5配置文件的abilities標簽中,針對需要添加快捷方式的UIAbility進行配置metadata標簽,使shortcut配置文件對該UIAbility生效。
{"module": {// ..."abilities": [{"name": "EntryAbility","srcEntry": "./ets/entryability/EntryAbility.ets",// ..."metadata": [{"name": "ohos.ability.shortcuts", // 配置快捷方式,該值固定為ohos.ability.shortcuts"resource": "$profile:shortcuts_config" // 指定shortcuts信息的資源位置}]}]}
}
示例圖
四、示例
效果圖
示例代碼
shortcuts_config.json
{"shortcuts": [{"shortcutId": "1","label": "$string:create_short_cut_detail","icon": "$media:icon_create_shortcut","wants": [{"bundleName": "com.example.learnharmonyos","moduleName": "entry","abilityName": "ShortcutsEntryAbility","parameters": {"pageType": "1"}}]},{"shortcutId": "2","label": "$string:share_friend","icon": "$media:icon_share","wants": [{"bundleName": "com.example.learnharmonyos","moduleName": "entry","abilityName": "ShortcutsEntryAbility","parameters": {"pageType": "2"}}]}]
}
module.json5
"abilities": [{"name": "EntryAbility","srcEntry": "./ets/entryability/EntryAbility.ets","description": "$string:EntryAbility_desc","icon": "$media:layered_image","label": "$string:EntryAbility_label","startWindowIcon": "$media:startIcon","startWindowBackground": "$color:start_window_background","exported": true,"skills": [{"entities": ["entity.system.home"],"actions": ["action.system.home"]}],"metadata": [{// 配置快捷方式,該值固定為ohos.ability.shortcuts"name": "ohos.ability.shortcuts",// 指定shortcuts信息的資源位置"resource": "$profile:shortcuts_config"}]}]
BackToHomeComponent.ets
import { common, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';const TAG: string = '[BackToHomeComponent]';
const DOMAIN_NUMBER: number = 0xFF00;@Component
export struct BackToHomeComponent {pageName: string = ""build() {Button('回到首頁').fontColor($r('app.color.c_black')).fontWeight(FontWeight.Medium).fontSize(20).padding(10).onClick(() => {let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext// 在FuncAbility中通過調用terminateSelf()方法實現。// context為需要停止的UIAbility實例的AbilityContextlet wantInfo: Want = {deviceId: '', // deviceId為空表示本設備bundleName: 'com.example.learnharmonyos',moduleName: 'entry', // moduleName非必選abilityName: 'EntryAbility',parameters: {// 自定義信息info: this.pageName},}context.startAbility(wantInfo).then(() => {hilog.info(DOMAIN_NUMBER, TAG, 'startAbility EntryAbility 首頁 success.');}).catch((error: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, 'startAbility EntryAbility 首頁 failed.');})context.terminateSelf((err) => {if (err.code) {hilog.error(DOMAIN_NUMBER, TAG,`Failed to terminate self. Code is ${err.code}, message is ${err.message}`);return;}});})}
}
CreateShortCutInfo.ets
import { webview } from '@kit.ArkWeb'
import { BackToHomeComponent } from './BackToHomeComponent'@Entry
@Component
struct CreateShortCutInfo {private webviewController: webview.WebviewController = new webview.WebviewController();private url: string ='https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/typical-scenario-configuration-V5'build() {Column({ space: 10 }) {BackToHomeComponent({ pageName: "CreateShortCutInfo" })Web({ src: this.url, controller: this.webviewController })}.height('100%').width('100%')}
}
ShortCutShare.ets
import { BackToHomeComponent } from './BackToHomeComponent'@Entry
@Component
struct ShortCutShare {@State message: string = '分享成功';build() {Column({ space: 10 }) {BackToHomeComponent({ pageName: "ShortCutShare" })Text(this.message).fontSize(10).fontWeight(FontWeight.Bold).margin({ top: 20 })}.width('100%').height('100%')}
}
ShortcutsEntryAbility.ets
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';export default class ShortcutsEntryAbility extends UIAbility {shortcutsEntryAbilityWant: Want | undefined = undefinedonCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');this.shortcutsEntryAbilityWant = want;}onDestroy(): void {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');}onWindowStageCreate(windowStage: window.WindowStage): void {// Main window is created, set main page for this abilityhilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');let router = 'pages/shortcuts/CreateShortCutInfo'if (this.shortcutsEntryAbilityWant?.parameters?.pageType &&this.shortcutsEntryAbilityWant?.parameters?.pageType === '2') {router = 'pages/shortcuts/ShortCutShare'}windowStage.loadContent(router, (err) => {if (err.code) {hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');return;}hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');});}onWindowStageDestroy(): void {// Main window is destroyed, release UI related resourceshilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');}onForeground(): void {// Ability has brought to foregroundhilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');}onBackground(): void {// Ability has back to backgroundhilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');}
}