arkts-ui-widget-event-uiability.md 7.7 KB
Newer Older
W
wangkailong 已提交
1
# 通过router或call事件刷新卡片内容
Z
zhongjianfei 已提交
2 3 4 5


在卡片页面中可以通过**postCardAction**接口触发router事件或者call事件拉起UIAbility,然后由UIAbility刷新卡片内容,下面是这种刷新方式的简单示例。

W
wangkailong 已提交
6
## 通过router事件刷新卡片内容
Z
zhongjianfei 已提交
7

D
fix  
dujingcheng 已提交
8
说明:<br/>  本文主要介绍动态卡片的事件开发。对于静态卡片,请参见[FormLink](../../application-dev/reference/arkui-ts/ts-container-formlink.md)<br/>
J
jiangdayuan 已提交
9
- 在卡片页面通过注册Button的onClick点击事件回调,并在回调中调用**postCardAction**接口触发router事件拉起UIAbility。
Z
zhongjianfei 已提交
10 11 12 13 14 15 16 17 18 19 20
  
  ```ts
  let storage = new LocalStorage();
  @Entry(storage)
  @Component
  struct WidgetCard {
    @LocalStorageProp('detail') detail: string = 'init';
  
    build() {
      Column() {
        Button('跳转')
21
          .margin(20)
Z
zhongjianfei 已提交
22 23 24 25 26 27 28 29 30 31
          .onClick(() => {
            console.info('postCardAction to EntryAbility');
            postCardAction(this, {
              'action': 'router',
              'abilityName': 'EntryAbility', // 只能跳转到当前应用下的UIAbility
              'params': {
                'detail': 'RouterFromCard'
              }
            });
          })
32
        Text(`${this.detail}`)
Z
zhongjianfei 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
      }
      .width('100%')
      .height('100%')
    }
  }
  ```
  
- 在UIAbility的onCreate()或者onNewWant()生命周期中可以通过入参want获取卡片的formID和传递过来的参数信息,然后调用[updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform)接口刷新卡片。
  
  ```ts
  import UIAbility from '@ohos.app.ability.UIAbility';
  import formBindingData from '@ohos.app.form.formBindingData';
  import formProvider from '@ohos.app.form.formProvider';
  import formInfo from '@ohos.app.form.formInfo';
X
xuzhihao 已提交
47 48 49
  import AbilityConstant from '@ohos.app.ability.AbilityConstant';
  import Want from '@ohos.app.ability.Want';
  import Base from '@ohos.base'
Z
zhongjianfei 已提交
50 51 52
  
  export default class EntryAbility extends UIAbility {
    // 如果UIAbility第一次启动,在收到Router事件后会触发onCreate生命周期回调
X
xuzhihao 已提交
53
    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
J
jiangdayuan 已提交
54
      this.handleFormRouterEvent(want);
Z
zhongjianfei 已提交
55 56
    }
    // 如果UIAbility已在后台运行,在收到Router事件后会触发onNewWant生命周期回调
X
xuzhihao 已提交
57
    onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) {
J
jiangdayuan 已提交
58 59 60
      this.handleFormRouterEvent(want);
    }

X
xuzhihao 已提交
61
    handleFormRouterEvent(want: Want) {
J
jiangdayuan 已提交
62
      console.info('Want:' + JSON.stringify(want));
X
xuzhihao 已提交
63 64 65
      if (want.parameters && want.parameters[formInfo.FormParam.IDENTITY_KEY] !== undefined) {
        let curFormId = JSON.stringify(want.parameters[formInfo.FormParam.IDENTITY_KEY]);
        let message: string = JSON.parse(JSON.stringify(want.parameters.params)).detail;
Z
zhongjianfei 已提交
66
        console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
X
xuzhihao 已提交
67
        let formData: Record<string, string> = {
J
jiangdayuan 已提交
68
          "detail": message + ': UIAbility.', // 和卡片布局中对应
Z
zhongjianfei 已提交
69 70 71 72
        };
        let formMsg = formBindingData.createFormBindingData(formData)
        formProvider.updateForm(curFormId, formMsg).then((data) => {
          console.info('updateForm success.' + JSON.stringify(data));
X
xuzhihao 已提交
73
        }).catch((error: Base.BusinessError) => {
Z
zhongjianfei 已提交
74 75 76 77 78 79 80
          console.error('updateForm failed:' + JSON.stringify(error));
        })
      }
    }
    ...
  }
  ```
W
wangkailong 已提交
81

W
wangkailong 已提交
82
## 通过call事件刷新卡片内容
W
wangkailong 已提交
83 84

- 在使用**postCardAction**接口的call事件时,需要在FormExtensionAbility中的onAddForm生命周期回调中更新formId。
85
  
W
wangkailong 已提交
86 87 88
   ```ts
   import formBindingData from '@ohos.app.form.formBindingData';
   import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
X
xuzhihao 已提交
89
   import Want from '@ohos.app.ability.Want';
W
wangkailong 已提交
90 91
   
   export default class EntryFormAbility extends FormExtensionAbility {
X
xuzhihao 已提交
92 93 94 95 96 97 98 99
    onAddForm(want: Want) {
      let dataObj1: Record<string, string> | undefined;
      if (want.parameters && want.parameters["ohos.extra.param.key.form_identity"] != undefined) {
        let formId: string = JSON.parse(JSON.stringify(want.parameters["ohos.extra.param.key.form_identity"]));
        dataObj1 = {
          "formId": formId
        };
      }
W
wangkailong 已提交
100 101 102
      let obj1 = formBindingData.createFormBindingData(dataObj1);
      return obj1;
    }
X
xuzhihao 已提交
103
    ...
W
wangkailong 已提交
104 105 106 107 108 109 110 111 112 113 114 115
   };
   ```

- 在卡片页面通过注册Button的onClick点击事件回调,并在回调中调用**postCardAction**接口触发call事件至UIAbility。
  
  ```ts
  let storage = new LocalStorage();
  @Entry(storage)
  @Component
  struct WidgetCard {
    @LocalStorageProp('detail') detail: string = 'init';
    @LocalStorageProp('formId') formId: string = '0';
116
  
W
wangkailong 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    build() {
      Column() {
        Button('拉至后台')
          .margin('20%')
          .onClick(() => {
            console.info('postCardAction to EntryAbility');
            postCardAction(this, {
              'action': 'call',
              'abilityName': 'EntryAbility', // 只能拉起当前应用下的UIAbility
              'params': {
                'method': 'funA',
                'formId': this.formId,
                'detail': 'CallFromCard'
              }
            });
          })
        Text(`${this.detail}`).margin('20%')
      }
      .width('100%')
      .height('100%')
    }
  }
  ```
  
- 在UIAbility的onCreate生命周期中监听call事件所需的方法,然后在对应方法中调用[updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform)接口刷新卡片。
  
  ```ts
  import UIAbility from '@ohos.app.ability.UIAbility';
  import formBindingData from '@ohos.app.form.formBindingData';
  import formProvider from '@ohos.app.form.formProvider';
X
xuzhihao 已提交
147 148 149 150
  import Want from '@ohos.app.ability.Want';
  import Base from '@ohos.base'
  import rpc from '@ohos.rpc';
  import AbilityConstant from '@ohos.app.ability.AbilityConstant';
W
wangkailong 已提交
151
  
152
  const MSG_SEND_METHOD: string = 'funA';
X
xuzhihao 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

  class MyParcelable implements rpc.Parcelable {
    num: number;
    str: string;
    constructor(num: number, str: string) {
      this.num = num;
      this.str = str;
    }
    marshalling(messageSequence: rpc.MessageSequence): boolean {
      messageSequence.writeInt(this.num);
      messageSequence.writeString(this.str);
      return true;
    }
    unmarshalling(messageSequence: rpc.MessageSequence): boolean {
      this.num = messageSequence.readInt();
      this.str = messageSequence.readString();
      return true;
    }
  }

W
wangkailong 已提交
173
  // 在收到call事件后会触发callee监听的方法
X
xuzhihao 已提交
174
  let FunACall = (data: rpc.MessageSequence) => {
W
wangkailong 已提交
175
    // 获取call事件中传递的所有参数
X
xuzhihao 已提交
176
    let params: Record<string, string> = JSON.parse(data.readString())
W
wangkailong 已提交
177
    if (params.formId !== undefined) {
X
xuzhihao 已提交
178 179
      let curFormId: string = params.formId;
      let message: string = params.detail;
W
wangkailong 已提交
180
      console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
X
xuzhihao 已提交
181
      let formData: Record<string, string> = {
W
wangkailong 已提交
182 183
        "detail": message
      };
X
xuzhihao 已提交
184
      let formMsg: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData);
W
wangkailong 已提交
185 186
      formProvider.updateForm(curFormId, formMsg).then((data) => {
        console.info('updateForm success.' + JSON.stringify(data));
X
xuzhihao 已提交
187
      }).catch((error: Base.BusinessError) => {
W
wangkailong 已提交
188 189 190
        console.error('updateForm failed:' + JSON.stringify(error));
      })
    }
X
xuzhihao 已提交
191
    return new MyParcelable(1, 'aaa');
W
wangkailong 已提交
192
  }
X
xuzhihao 已提交
193

W
wangkailong 已提交
194 195
  export default class EntryAbility extends UIAbility {
    // 如果UIAbility第一次启动,call事件后会触发onCreate生命周期回调
X
xuzhihao 已提交
196
    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
W
wangkailong 已提交
197 198
      console.info('Want:' + JSON.stringify(want));
      try {
X
xuzhihao 已提交
199
        // 监听call事件所需的方法
W
wangkailong 已提交
200 201
        this.callee.on(MSG_SEND_METHOD, FunACall);
      } catch (error) {
X
xuzhihao 已提交
202
        console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error as Base.BusinessError)}`)
W
wangkailong 已提交
203 204 205 206
      }
    }
  }
  ```