使用call事件拉起指定UIAbility到后臺
許多應用希望借助卡片的能力,實現和應用在前臺時相同的功能。例如音樂卡片,卡片上提供播放、暫停等按鈕,點擊不同按鈕將觸發音樂應用的不同功能,進而提高用戶的體驗。在卡片中使用postCardAction接口的call能力,能夠將卡片提供方應用的指定UIAbility拉到后臺。同時,call能力提供了調用應用指定方法、傳遞數據的功能,使應用在后臺運行時可以通過卡片上的按鈕執行不同的功能。
通常使用按鈕控件來觸發call事件,示例代碼如下:
-
在卡片頁面中布局兩個按鈕,點擊其中一個按鈕時調用postCardAction向指定UIAbility發送call事件,并在事件內定義需要調用的方法和傳遞的數據。需要注意的是,method參數為必選參數,且類型需要為string類型,用于觸發UIAbility中對應的方法。
@Entry @Component struct WidgetCard {build() {Column() {Button('功能A').margin('20%').onClick(() => {console.info('call EntryAbility funA');postCardAction(this, {'action': 'call','abilityName': 'EntryAbility', // 只能跳轉到當前應用下的UIAbility'params': {'method': 'funA' // 在EntryAbility中調用的方法名}});})Button('功能B').margin('20%').onClick(() => {console.info('call EntryAbility funB');postCardAction(this, {'action': 'call','abilityName': 'EntryAbility', // 只能跳轉到當前應用下的UIAbility'params': {'method': 'funB', // 在EntryAbility中調用的方法名'num': 1 // 需要傳遞的其他參數}});})}.width('100%').height('100%')} }
-
在UIAbility中接收call事件并獲取參數,根據傳遞的method不同,執行不同的方法。其余數據可以通過readString的方式獲取。需要注意的是,UIAbility需要onCreate生命周期中監聽所需的方法。
import UIAbility from '@ohos.app.ability.UIAbility';function FunACall(data) {// 獲取call事件中傳遞的所有參數console.log('FunACall param:' + JSON.stringify(data.readString()));return null; }function FunBCall(data) {console.log('FunACall param:' + JSON.stringify(data.readString()));return null; }export default class CameraAbility extends UIAbility {// 如果UIAbility第一次啟動,在收到call事件后會觸發onCreate生命周期回調onCreate(want, launchParam) {try {// 監聽call事件所需的方法this.callee.on('funA', FunACall);this.callee.on('funB', FunBCall);} catch (error) {console.log('register failed with error. Cause: ' + JSON.stringify(error));}}// 進程退出時,解除監聽onDestroy() {try {this.callee.off('funA');this.callee.off('funB');} catch (error) {console.log('register failed with error. Cause: ' + JSON.stringify(error));}} };