arkts-ui-widget-update-by-status.md 7.7 KB
Newer Older
Z
zhongjianfei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 根据卡片状态刷新不同内容


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


- 卡片配置文件:配置每天早上7点触发定时刷新
  
  ```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';
Z
zhongjianfei 已提交
99 100 101
  
  export default class EntryFormAbility extends FormExtensionAbility {
    onAddForm(want) {
102 103 104 105
      let formId = want.parameters[formInfo.FormParam.IDENTITY_KEY];
      let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY];
      if (isTempCard === false) { // 如果为常态卡片,直接进行信息持久化
        console.info('Not temp card, init db for:' + formId);
106
        let promise = dataPreferences.getPreferences(this.context, 'myStore');
107
        promise.then(async (storeDB) => {
108
          console.info("Succeeded to get preferences.");
109 110 111
          await storeDB.put('A' + formId, 'false');
          await storeDB.put('B' + formId, 'false');
          await storeDB.flush();
112 113 114
        }).catch((err) => {
          console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
        })
115
      }
Z
zhongjianfei 已提交
116 117 118 119 120 121
      let formData = {};
      return formBindingData.createFormBindingData(formData);
    }
  
    onRemoveForm(formId) {
      console.info('onRemoveForm, formId:' + formId);
122
      let promise = dataPreferences.getPreferences(this.context, 'myStore');
123
      promise.then(async (storeDB) => {
124
        console.info("Succeeded to get preferences.");
125 126
        await storeDB.delete('A' + formId);
        await storeDB.delete('B' + formId);
127 128 129
      }).catch((err) => {
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
130 131
    }
  
132
    // 如果在添加时为临时卡片,则建议转为常态卡片时进行信息持久化
Z
zhongjianfei 已提交
133 134
    onCastToNormalForm(formId) {
      console.info('onCastToNormalForm, formId:' + formId);
135
      let promise = dataPreferences.getPreferences(this.context, 'myStore');
136
      promise.then(async (storeDB) => {
137
        console.info("Succeeded to get preferences.");
138 139 140
        await storeDB.put('A' + formId, 'false');
        await storeDB.put('B' + formId, 'false');
        await storeDB.flush();
141 142 143
      }).catch((err) => {
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
144 145 146
    }
  
    onUpdateForm(formId) {
147
      let promise = dataPreferences.getPreferences(this.context, 'myStore');
148
      promise.then(async (storeDB) => {
149
        console.info("Succeeded to get preferences.");
150 151
        let stateA = await storeDB.get('A' + formId, 'false');
        let stateB = await storeDB.get('B' + formId, 'false');
152 153 154
        // A状态选中则更新textA
        if (stateA === 'true') {
          let formInfo = formBindingData.createFormBindingData({'textA': 'AAA'});
155
          await formProvider.updateForm(formId, formInfo);
156 157 158 159
        }
        // B状态选中则更新textB
        if (stateB === 'true') {
          let formInfo = formBindingData.createFormBindingData({'textB': 'BBB'});
160
          await formProvider.updateForm(formId, formInfo);
161 162 163 164 165
        }
        console.info(`Update form success stateA:${stateA} stateB:${stateB}.`);
      }).catch((err) => {
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
166 167 168 169 170
    }
  
    onFormEvent(formId, message) {
      // 存放卡片状态
      console.info('onFormEvent formId:' + formId + 'msg:' + message);
171
      let promise = dataPreferences.getPreferences(this.context, 'myStore');
172
      promise.then(async (storeDB) => {
173 174 175 176
        console.info("Succeeded to get preferences.");
        let msg = JSON.parse(message);
        if (msg.selectA != undefined) {
          console.info('onFormEvent selectA info:' + msg.selectA);
177
          await storeDB.put('A' + formId, msg.selectA);
178 179 180
        }
        if (msg.selectB != undefined) {
          console.info('onFormEvent selectB info:' + msg.selectB);
181
          await storeDB.put('B' + formId, msg.selectB);
182
        }
183
        await storeDB.flush();
184 185 186
      }).catch((err) => {
        console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
      })
Z
zhongjianfei 已提交
187 188 189 190 191
    }
  };
  ```


192 193
> **说明:**
>
194 195
> 通过本地数据库进行卡片信息的持久化时,建议先在[**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)**)时删除当前卡片存储的持久化信息,避免反复添加删除卡片导致数据库文件持续变大。