信息傳遞載體Want
1、概述
上一章節我們學習了UIAbility組件 【最新鴻蒙應用開發】——一篇搞懂什么是UIAbility-CSDN博客
,其中組件間的交互傳遞信息的媒介就是Want
,本章節我們來更加深入學習Want
的相關知識。 Want
是一種對象,用于在應用組件之間傳遞信息。
2、類型
-
顯式Want
:在啟動目標應用組件時,調用方傳入的want
參數中指定了abilityName
和bundleName
,稱為顯式Want
。 -
隱式Want
:在啟動目標應用組件時,調用方傳入的want
參數中未指定abilityName
,稱為隱式Want
。
import Want from '@ohos.app.ability.Want';
?
// 1. 顯式Want
let wantInfo: Want = {deviceId: '', // deviceId為空表示本設備bundleName: 'com.example.myapplication',abilityName: 'FuncAbility',
}
?
// 2. 隱式Want
let wantInfo: Want = {// uncomment line below if wish to implicitly query only in the specific bundle.// bundleName: 'com.example.myapplication',action: 'ohos.want.action.search',// entities can be omittedentities: [ 'entity.system.browsable' ],uri: 'https://www.test.com:8080/query/student',type: 'text/plain',
};
3、匹配規則
調用方傳入的want
參數中設置的參數如何與目標應用組件聲明的配置文件進行匹配,需要時查看參考文檔即可。
顯式Want與隱式Want匹配規則 (openharmony.cn)
4、使用場景
-
在調用startAbility()方法時,其入參want中指定了一系列的entities字段(表示目標UIAbility額外的類別信息,如瀏覽器、視頻播放器)和actions字段(表示要執行的通用操作,如查看、分享、應用詳情等)等參數信息,
-
然后由系統去分析want,并幫助找到合適的UIAbility來啟動。
使用顯式Want啟動應用組件
在應用使用場景中,當用戶在應用內點擊某個按鈕時,經常需要拉起指定UIAbility組件來完成某些特定任務。在啟動UIAbility時,指定了abilityName和bundleName參數,可以使用顯式Want方式啟動UIAbility。
針對應用的特定任務,用戶需要通過點擊應用內的按鈕來啟動指定的UIAbility組件。在啟動UIAbility時,需要提供abilityName和bundleName參數,并使用顯式Want方式來啟動。
使用隱式Want打開網址
以打開瀏覽器為例,假設設備上安裝了一個或多個瀏覽器應用。為了使瀏覽器應用能夠正常工作,需要在module.json5配置文件進行配置,具體配置如下:
{"module": {"abilities": [{//入口配置"skills": [{"actions": ["action.system.home"],"entities": ["entity.system.home"]},//瀏覽器配置{"actions": ["ohos.want.action.viewData"],"entities": ["entity.system.browsable"],"uris": [{"scheme": "https","host": "www.test.com","port": "8080","pathStartWith": "query"},{"scheme": "http"}]}]}]}
}
在調用方UIAbility中,使用隱式Want方式啟動瀏覽器應用。
import common from '@ohos.app.ability.common';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
?
let context = getContext(this) as common.UIAbilityContext;
let wantInfo: Want = {// uncomment line below if wish to implicitly query only in the specific bundle.// bundleName: 'com.example.myapplication',action: 'ohos.want.action.viewData',// entities can be omitted.entities: ['entity.system.browsable'],uri: 'https://www.test.com:8080/query/student'
}
context.startAbility(wantInfo).then(() => {// ...
}).catch((err: BusinessError) => {// ...
})
匹配過程分析:
-
調用方傳入的want參數的action不為空,待匹配目標應用組件的skills配置中的actions不為空且包含調用方傳入的want參數的action,action匹配成功。
-
調用方傳入的want參數的entities不為空,待匹配目標應用組件的skills配置中的entities不為空且包含調用方傳入的want參數的entities,entities匹配成功。
-
待匹配目標應用組件的skills配置中內uris拼接為
https://www.test.com:8080/query*
(其中*表示通配符),包含調用方傳入的want參數的uri,uri匹配成功。
當存在多個匹配的應用時,系統將彈出應用選擇框供用戶選擇。示意效果如下圖所示。
應用間使用Want分享數據
在應用使用場景中,用戶經常需要將應用內的數據(如文字、圖片等)分享至其他應用以供進一步處理。Want支持實現應用間的數據分享,具體指導請參見應用文件分享。
參考文獻: OpenHarmoney應用開發文檔Want概述