鴻蒙意圖框架Intents Kit如何使用

意圖框架是什么

意圖框架能幫開發(fā)者將應(yīng)用/元服務(wù)內(nèi)的業(yè)務(wù)功能,智能分發(fā)到各系統(tǒng)入口,這個(gè)過程即智慧分發(fā)。其中系統(tǒng)入口包括:小藝對(duì)話、小藝搜索、小藝建議

001.png

意圖框架分發(fā)的類型

002.png

意圖的運(yùn)行邏輯

003.png
004.png

意圖框架接入流程

005.png

習(xí)慣推薦方案實(shí)現(xiàn)

當(dāng)前習(xí)慣推薦可在小藝建議入口分發(fā),在不同垂域中,填充功能詳細(xì)參數(shù)或內(nèi)容的邏輯不同,主要典型場(chǎng)景可分為常用接續(xù)、常用復(fù)訪、常用推新三類。

當(dāng)用戶在應(yīng)用/元服務(wù)內(nèi)使用功能時(shí),開發(fā)者需要按照標(biāo)準(zhǔn)意圖Schema向系統(tǒng)共享行為數(shù)據(jù),并支持意圖調(diào)用(空調(diào)用與傳參調(diào)用),以實(shí)現(xiàn)用戶點(diǎn)擊模板卡后跳轉(zhuǎn)回對(duì)應(yīng)頁面。

006.png

意圖注冊(cè)

開發(fā)者需要編輯對(duì)應(yīng)的意圖配置 PROJECT_HOME/entry/src/main/resources/base/profile/insight_intent.json文件,實(shí)現(xiàn)意圖注冊(cè)。以歌曲續(xù)聽推薦特性為例:

{
  // 應(yīng)用支持的意圖列表
  // 必須聲明應(yīng)用支持插件包含的必選意圖,應(yīng)用上架時(shí)會(huì)進(jìn)行校驗(yàn)
  "insightIntents": [
    {
      // 意圖名稱
      // 名稱應(yīng)當(dāng)遵循意圖框架規(guī)范,當(dāng)前僅支持預(yù)置垂域意圖,不允許自定義
      // 應(yīng)用內(nèi)意圖名稱唯一,不允許出現(xiàn)相同的名稱定義
      "intentName": "PlayMusic",
      // 意圖所屬的垂域
      "domain": "MusicDomain",
      // 意圖版本號(hào)
      // 插件引用意圖時(shí)會(huì)校驗(yàn)該版本號(hào),只有和插件定義的版本號(hào)一致才能正常調(diào)用
      "intentVersion": "1.0.1",
      // 意圖調(diào)用邏輯入口
      // 根據(jù)意圖調(diào)用文件實(shí)際路徑和實(shí)際名稱進(jìn)行填寫,此處文件僅做示意
      "srcEntry": "./ets/entryability/InsightIntentExecutorImpl.ets",
      "uiAbility": {
        // 意圖所在module、ability,以及代碼相對(duì)路徑入口
        "ability": "EntryAbility",
        // UIAbility支持前后臺(tái)兩種執(zhí)行模式
        "executeMode": [
          "background",
          "foreground"
        ]
      }
    }
  ]
}

端側(cè)意圖共享

構(gòu)建意圖對(duì)象,并且調(diào)用shareIntent(),實(shí)現(xiàn)意圖共享??赏瑫r(shí)構(gòu)建多個(gè)PlayMusic或PlayMusicList的意圖對(duì)象。

import { insightIntent } from '@kit.IntentsKit';
import { BusinessError } from '@kit.BasicServicesKit';

let playMusicIntent1: insightIntent.InsightIntent;
let playMusicIntent2: insightIntent.InsightIntent;
// 共享數(shù)據(jù)接口  意圖數(shù)組可以是更多的實(shí)體
// 根據(jù)實(shí)際代碼上下文自行傳入合適的context
insightIntent.shareIntent(context, [playMusicIntent1, playMusicIntent2]).then(() => {
  console.info('shareIntent succeed');
}).catch((err: BusinessError) => {
  console.error(`error.code: ${err?.code}, failed because ${err?.message}`);
});

完整的意圖共享示例如下所示,該示例構(gòu)建了一個(gè)PlayMusic意圖,并進(jìn)行了shareIntent調(diào)用。

import { insightIntent } from '@kit.IntentsKit';
import { BusinessError } from '@kit.BasicServicesKit';

let playMusicIntent: insightIntent.InsightIntent = {
  intentName: "PlayMusic",
  intentVersion: "1.0",
  identifier: "52dac3b0-6520-4974-81e5-25f0879449b5",
  intentActionInfo: {
    actionMode: "EXECUTED",
    executedTimeSlots: {
      executedStartTime: 1637393212000,
      executedEndTime: 1637393112000,
    },
    currentPercentage: 50,
  },
  intentEntityInfo: {
    entityName: "Music",
    entityId: "C10194368",
    entityGroupId: "C10194321312",
    displayName: "測(cè)試歌曲1",
    description: "NA",
    logoURL: "https://www-file.abc.com/-/media/corporate/images/home/logo/abc_logo.png",
    keywords: ["華為音樂", "化妝"],
    rankingHint: 99,
    expirationTime: 1637393212000,
    metadataModificationTime: 1637393212000,
    activityType: ["1", "2", "3"],
    artist: ["測(cè)試歌手1", "測(cè)試歌手2"],
    lyricist: ["測(cè)試詞作者1", "測(cè)試詞作者2"],
    composer: ["測(cè)試曲作者1", "測(cè)試曲作者2"],
    albumName: "測(cè)試專輯",
    duration: 244000,
    playCount: 100000,
    musicalGenre: ["流行", "華語", "金曲", "00后"],
    isPublicData: false,
  }
}
// 共享數(shù)據(jù)接口  意圖數(shù)組可以是更多的實(shí)體
// 根據(jù)實(shí)際代碼上下文自行傳入合適的context
insightIntent.shareIntent(context, [playMusicIntent]).then(() => {
  console.info('shareIntent succeed');
}).catch((err: BusinessError) => {
  console.error(`error.code: ${err?.code}, failed because ${err?.message}`);
});

端側(cè)意圖調(diào)用

意圖執(zhí)行組件為uiAbility的意圖調(diào)用

步驟如下:

  1. 繼承InsightIntentExecutor。
  2. 重寫對(duì)應(yīng)方法,例如目標(biāo)拉起前臺(tái)頁面,則可重寫onExecuteInUIAbilityForegroundMode方法。
  3. 通過意圖名稱,識(shí)別播放歌曲意圖(PlayMusic),在對(duì)應(yīng)的方法中傳遞意圖參數(shù)(param),并拉起對(duì)應(yīng)落地頁(如歌曲落地頁)。
import { insightIntent, InsightIntentExecutor } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

/**
 * 意圖調(diào)用樣例
 */
export default class InsightIntentExecutorImpl extends InsightIntentExecutor {
  private static readonly PLAY_MUSIC = 'PlayMusic';
  /**
   * override 執(zhí)行前臺(tái)UIAbility意圖
   *
   * @param name 意圖名稱
   * @param param 意圖參數(shù)
   * @param pageLoader 窗口
   * @returns 意圖調(diào)用結(jié)果
   */
  onExecuteInUIAbilityForegroundMode(name: string, param: Record<string, Object>, pageLoader: window.WindowStage):
    Promise<insightIntent.ExecuteResult> {
    //根據(jù)意圖名稱分發(fā)處理邏輯。接入方可根據(jù)實(shí)際業(yè)務(wù)實(shí)現(xiàn)頁面跳轉(zhuǎn)
    switch (name) {
      case InsightIntentExecutorImpl.PLAY_MUSIC:
        return this.playMusic(param, pageLoader);
      default:
        break;
    }
    return Promise.resolve({
      code: -1,
      result: {
        message: 'unknown intent'
      }
    } as insightIntent.ExecuteResult)
  }
  /**
   * 實(shí)現(xiàn)調(diào)用播放歌曲功能
   *
   * @param param 意圖參數(shù)
   * @param pageLoader 窗口
   */
  private playMusic(param: Record<string, Object>, pageLoader: window.WindowStage): Promise<insightIntent.ExecuteResult> {
    return new Promise((resolve, reject) => {
      let para: Record<string, string> = {
        'result': JSON.stringify(param)
      };
      let localStorage: LocalStorage = new LocalStorage(para);
      // TODO 實(shí)現(xiàn)意圖調(diào)用,loadContent的入?yún)楦枨涞仨撀窂?,例如:pages/Index
      pageLoader.loadContent('pages/Index', localStorage)
        .then(() => {
          let entityId: string = (param.items as Array<object>)?.[0]?.['entityId'];
          // TODO 調(diào)用成功的情況,此處可以打印日志
          resolve({
            code: 0,
            result: {
              message: 'Intent execute succeed'
            }
          });
        })
        .catch((err: BusinessError) => {
          // TODO 調(diào)用失敗的情況
          resolve({
            code: -1,
            result: {
              message: 'Intent execute failed'
            }
          })
        });
    })
  }
}

意圖執(zhí)行組件為form的意圖調(diào)用

  1. 在意圖執(zhí)行綁定FormExtensionAbility的onAddForm(want: Want)中獲取運(yùn)行態(tài)意圖框架傳入的意圖名(預(yù)定義keyName為ohos.insightIntent.executeParam.name)和意圖執(zhí)行參數(shù)(預(yù)定義keyName為ohos.insightIntent.executeParam.param);
  2. 通過意圖名稱,識(shí)別播放歌曲意圖(PlayMusic),在對(duì)應(yīng)的方法中傳遞意圖參數(shù)(param),并加載對(duì)應(yīng)數(shù)據(jù)用于卡片展示。

具體代碼實(shí)現(xiàn):

import { Want } from '@kit.AbilityKit';
import { formBindingData, FormExtensionAbility } from '@kit.FormKit';

/**
 * 卡片意圖調(diào)用示例
 */
export default class LoadCardFormAbility extends FormExtensionAbility {
  onAddForm(want: Want): formBindingData.FormBindingData {
    if (want?.parameters?.['ohos.insightIntent.executeParam.name'] != undefined) {
      const intentName = want.parameters['ohos.insightIntent.executeParam.name']; //意圖名
      //TODO: 根據(jù)意圖名稱分發(fā)處理邏輯,若僅一個(gè)卡片意圖,則可以忽略
    }

    if (want?.parameters?.['ohos.insightIntent.executeParam.param'] != undefined) {
      const executeParameter = want.parameters['ohos.insightIntent.executeParam.param']; //意圖執(zhí)行參數(shù)
      //TODO: 從 executeParameter 中解析具體意圖執(zhí)行參數(shù),用于卡片內(nèi)容展示
    }

    let formData = ''; //TODO: 僅示例,根據(jù)具體邏輯封裝
    return formBindingData.createFormBindingData(formData);
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容