arkts-ui-widget-update-by-status.md 8.4 KB
Newer Older
Z
zhongjianfei 已提交
1 2 3 4 5 6
# 根据卡片状态刷新不同内容


相同的卡片可以添加到桌面上实现不同的功能,比如添加两张桌面的卡片,一张显示杭州的天气,一张显示北京的天气,设置每天早上7点触发定时刷新,卡片需要感知当前的配置是杭州还是北京,然后将对应城市的天气信息刷新到卡片上,以下示例介绍了如何根据卡片的状态动态选择需要刷新的内容。


W
form  
wangkailong 已提交
7
- 卡片配置文件:配置每天早上7点触发定时刷新。
Z
zhongjianfei 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
  
  ```json
  {
    "forms": [
      {
        "name": "widget",
        "description": "This is a service widget.",
        "src": "./ets/widget/pages/WidgetCard.ets",
        "uiSyntax": "arkts",
        "window": {
          "designWidth": 720,
          "autoDesignWidth": true
        },
        "colorMode": "auto",
        "isDefault": true,
23 24
        "updateEnabled": true,
        "scheduledUpdateTime": "07:00",
Z
zhongjianfei 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        "updateDuration": 0,
        "defaultDimension": "2*2",
        "supportDimensions": ["2*2"]
      }
    ]
  }
  ```

- 卡片页面:卡片具备不同的状态选择,在不同的状态下需要刷新不同的内容,因此在状态发生变化时通过postCardAction通知EntryFormAbility。
  
  ```ts
  let storage = new LocalStorage();
  @Entry(storage)
  @Component
  struct WidgetCard {
    @LocalStorageProp('textA') textA: string = '待刷新...';
    @LocalStorageProp('textB') textB: string = '待刷新...';
    @State selectA: boolean = false;
    @State selectB: boolean = false;
  
    build() {
      Column() {
        Row() {
          Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
            .select(false)
            .onChange((value: boolean) => {
              this.selectA = value;
              postCardAction(this, {
                'action': 'message',
                'params': {
                  'selectA': JSON.stringify(value)
                }
              });
            })
          Text('状态A')
        }
  
        Row() {
          Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
            .select(false)
            .onChange((value: boolean) => {
              this.selectB = value;
              postCardAction(this, {
                'action': 'message',
                'params': {
                  'selectB': JSON.stringify(value)
                }
              });
            })
          Text('状态B')
        }
  
        Row() { // 选中状态A才会进行刷新的内容
          Text('状态A: ')
          Text(this.textA)
        }
  
        Row() { // 选中状态B才会进行刷新的内容
          Text('状态B: ')
          Text(this.textB)
        }
      }.padding('10%')
    }
  }
  ```
  
- EntryFormAbility:将卡片的状态存储在本地数据库中,在刷新事件回调触发时,通过formId获取当前卡片的状态,然后根据卡片的状态选择不同的刷新内容。
  
  ```ts
94
  import formInfo from '@ohos.app.form.formInfo'
Z
zhongjianfei 已提交
95 96 97
  import formProvider from '@ohos.app.form.formProvider';
  import formBindingData from '@ohos.app.form.formBindingData';
  import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
Y
yuyaozhi 已提交
98
  import dataPreferences from '@ohos.data.preferences';
X
xuzhihao 已提交
99 100
  import Want from '@ohos.app.ability.Want';
  import Base from '@ohos.base';
Z
zhongjianfei 已提交
101 102
  
  export default class EntryFormAbility extends FormExtensionAbility {
X
xuzhihao 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    onAddForm(want: Want) {
      let formId: string = '';
      let isTempCard: boolean;
      if (want.parameters) {
        formId = JSON.stringify(want.parameters[formInfo.FormParam.IDENTITY_KEY]);
        isTempCard = want.parameters[formInfo.FormParam.TEMPORARY_KEY] as boolean;
        if (isTempCard === false) { // 如果为常态卡片,直接进行信息持久化
          console.info('Not temp card, init db for:' + formId);
          let promise: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(this.context, 'myStore');
          promise.then(async (storeDB: dataPreferences.Preferences) => {
            console.info("Succeeded to get preferences.");
            await storeDB.put('A' + formId, 'false');
            await storeDB.put('B' + formId, 'false');
            await storeDB.flush();
          }).catch((err: Base.BusinessError) => {
            console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
          })
        }
121
      }
X
xuzhihao 已提交
122
      let formData: Record<string, Object | string> = {};
Z
zhongjianfei 已提交
123 124
      return formBindingData.createFormBindingData(formData);
    }
X
xuzhihao 已提交
125 126

    onRemoveForm(formId: string) {
Z
zhongjianfei 已提交
127
      console.info('onRemoveForm, formId:' + formId);
128
      let promise = dataPreferences.getPreferences(this.context, 'myStore');
129
      promise.then(async (storeDB) => {
130
        console.info("Succeeded to get preferences.");
131 132
        await storeDB.delete('A' + formId);
        await storeDB.delete('B' + formId);
X
xuzhihao 已提交
133
      }).catch((err: Base.BusinessError) => {
134 135
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
136
    }
X
xuzhihao 已提交
137

138
    // 如果在添加时为临时卡片,则建议转为常态卡片时进行信息持久化
X
xuzhihao 已提交
139
    onCastToNormalForm(formId: string) {
Z
zhongjianfei 已提交
140
      console.info('onCastToNormalForm, formId:' + formId);
X
xuzhihao 已提交
141 142
      let promise: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(this.context, 'myStore');
      promise.then(async (storeDB: dataPreferences.Preferences) => {
143
        console.info("Succeeded to get preferences.");
144 145 146
        await storeDB.put('A' + formId, 'false');
        await storeDB.put('B' + formId, 'false');
        await storeDB.flush();
X
xuzhihao 已提交
147
      }).catch((err: Base.BusinessError) => {
148 149
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
150
    }
X
xuzhihao 已提交
151 152 153 154

    onUpdateForm(formId: string) {
      let promise: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(this.context, 'myStore');
      promise.then(async (storeDB: dataPreferences.Preferences) => {
155
        console.info("Succeeded to get preferences.");
156 157
        let stateA = await storeDB.get('A' + formId, 'false');
        let stateB = await storeDB.get('B' + formId, 'false');
158 159 160
        // A状态选中则更新textA
        if (stateA === 'true') {
          let formInfo = formBindingData.createFormBindingData({'textA': 'AAA'});
161
          await formProvider.updateForm(formId, formInfo);
162 163 164 165
        }
        // B状态选中则更新textB
        if (stateB === 'true') {
          let formInfo = formBindingData.createFormBindingData({'textB': 'BBB'});
166
          await formProvider.updateForm(formId, formInfo);
167 168
        }
        console.info(`Update form success stateA:${stateA} stateB:${stateB}.`);
X
xuzhihao 已提交
169
      }).catch((err: Base.BusinessError) => {
170 171
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
172
    }
X
xuzhihao 已提交
173 174

    onFormEvent(formId: string, message: string) {
Z
zhongjianfei 已提交
175 176
      // 存放卡片状态
      console.info('onFormEvent formId:' + formId + 'msg:' + message);
X
xuzhihao 已提交
177 178
      let promise: Promise<dataPreferences.Preferences> = dataPreferences.getPreferences(this.context, 'myStore');
      promise.then(async (storeDB: dataPreferences.Preferences) => {
179
        console.info("Succeeded to get preferences.");
X
xuzhihao 已提交
180
        let msg: Record<string, string> = JSON.parse(message);
181 182
        if (msg.selectA != undefined) {
          console.info('onFormEvent selectA info:' + msg.selectA);
183
          await storeDB.put('A' + formId, msg.selectA);
184 185 186
        }
        if (msg.selectB != undefined) {
          console.info('onFormEvent selectB info:' + msg.selectB);
187
          await storeDB.put('B' + formId, msg.selectB);
188
        }
189
        await storeDB.flush();
X
xuzhihao 已提交
190
      }).catch((err: Base.BusinessError) => {
191 192
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
193 194 195 196 197
    }
  };
  ```


198 199
> **说明:**
>
200 201
> 通过本地数据库进行卡片信息的持久化时,建议先在[**onAddForm**](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform)生命周期中通过[**TEMPORARY_KEY**](../reference/apis/js-apis-app-form-formInfo.md#formparam)判断当前添加的卡片是否为常态卡片:如果是常态卡片,则直接进行卡片信息持久化;如果为临时卡片,则可以在卡片转为常态卡片(**[onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)**)时进行持久化;同时需要在卡片销毁(**[onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)**)时删除当前卡片存储的持久化信息,避免反复添加删除卡片导致数据库文件持续变大。