W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
許多應(yīng)用希望借助卡片的能力,實(shí)現(xiàn)和應(yīng)用在前臺(tái)時(shí)相同的功能。例如音樂卡片,卡片上提供播放、暫停等按鈕,點(diǎn)擊不同按鈕將觸發(fā)音樂應(yīng)用的不同功能,進(jìn)而提高用戶的體驗(yàn)。在卡片中使用postCardAction接口的call能力,能夠?qū)⒖ㄆ峁┓綉?yīng)用的指定UIAbility拉到后臺(tái)。同時(shí),call能力提供了調(diào)用應(yīng)用指定方法、傳遞數(shù)據(jù)的功能,使應(yīng)用在后臺(tái)運(yùn)行時(shí)可以通過卡片上的按鈕執(zhí)行不同的功能。
通常使用按鈕控件來觸發(fā)call事件,示例代碼如下:
- @Entry
- @Component
- struct WidgetCard {
- build() {
- Column() {
- Button('功能A')
- .margin('20%')
- .onClick(() => {
- console.info('call EntryAbility funA');
- postCardAction(this, {
- 'action': 'call',
- 'abilityName': 'EntryAbility', // 只能跳轉(zhuǎn)到當(dāng)前應(yīng)用下的UIAbility
- 'params': {
- 'method': 'funA' // 在EntryAbility中調(diào)用的方法名
- }
- });
- })
- Button('功能B')
- .margin('20%')
- .onClick(() => {
- console.info('call EntryAbility funB');
- postCardAction(this, {
- 'action': 'call',
- 'abilityName': 'EntryAbility', // 只能跳轉(zhuǎn)到當(dāng)前應(yīng)用下的UIAbility
- 'params': {
- 'method': 'funB', // 在EntryAbility中調(diào)用的方法名
- 'num': 1 // 需要傳遞的其他參數(shù)
- }
- });
- })
- }
- .width('100%')
- .height('100%')
- }
- }
- import UIAbility from '@ohos.app.ability.UIAbility';
- function FunACall(data) {
- // 獲取call事件中傳遞的所有參數(shù)
- 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第一次啟動(dòng),在收到call事件后會(huì)觸發(fā)onCreate生命周期回調(diào)
- onCreate(want, launchParam) {
- try {
- // 監(jiān)聽call事件所需的方法
- this.callee.on('funA', FunACall);
- this.callee.on('funB', FunBCall);
- } catch (error) {
- console.log('register failed with error. Cause: ' + JSON.stringify(error));
- }
- }
- // 進(jìn)程退出時(shí),解除監(jiān)聽
- onDestroy() {
- try {
- this.callee.off('funA');
- this.callee.off('funB');
- } catch (error) {
- console.log('register failed with error. Cause: ' + JSON.stringify(error));
- }
- }
- };
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: