HarmonyOS 鸿蒙Next UIAbility主动更新卡片信息

1 缘起

鸿蒙的服务卡片可以桌面展示直观信息,使用起来非常有趣,我想通过应用来更新卡片信息,但next文档长这样:

image.png

于是通过搜索和研究,总结技术经验在此。

2 应用方更新卡片数据的主要方法

1)获取formID -> 2) formProvider提交更新数据 -> 3)卡片方更新数据

3 缘落

3.1 获取formID

 因为应用方无法知道服务卡片的formID,因此要在服务卡片创建的时候把fromID存起来,主要是通过首选项进行。在卡片的onAddForm函数中存储当前formID:
  onAddForm(want: Want) {
    // Called to return a FormBindingData object.
    let formId: string = want.parameters?.[formInfo.FormParam.IDENTITY_KEY] as string;

    let options: preferences.Options = { name: 'trainCard' };
    let dataP = preferences.getPreferencesSync(this.context, options);
    dataP.putSync("formid",formId);
    dataP.flush();
}

然后在需要更新数据时再把formID读出来:

   let context = getContext(this) as common.UIAbilityContext
    let dataPreferences: preferences.Preferences | null = null;
    let options: preferences.Options = { name: 'trainCard' };
    dataPreferences = preferences.getPreferencesSync(context, options);
    //读取数据
    if (dataPreferences != null) {

      let teststr = dataPreferences.getSync('formid','');

      this.formId = teststr.toString();
    }

3.2 formProvider提交更新数据

 formProvider模块提供了更新卡片,设置卡片更新时间,获取卡片信息,请求发布卡片等接口。其中formProvider.updateForm方法用来更新指定的卡片。
    let obj: Record<string, string> = {
      "title":"我更新了"
    }            
    if (this.formId == '') {
              this.tocast = "请拉伸为卡片后再试";
              //创建卡片
            } else {
              let formData:formBindingData.FormBindingData = formBindingData.createFormBindingData(obj);
              formProvider.updateForm(this.formId, formData).catch((error: BusinessError) => {
                console.log('updateForm, error:' + JSON.stringify(error));
              });
          }

3.3 卡片方更新数据

   卡片页面通过localStorageProp接收数据。首先在WidgetCard.ets页面的最上面创建一个LocalStorage的实例,然后将实例传递给@Entry,在页面中就可以使用LocalStorageProp修饰符来接收数据了。
const storage = new LocalStorage();

@Entry(storage)
@Component
struct WidgetCard {
 // 接收 EntryFormAbility 传递过来的数据
  @LocalStorageProp("title") title: string = '';
    build() {
    Column() {
      Text(this.title)
    }
    .width("100%")
    .height("100%")
}

更多关于HarmonyOS 鸿蒙Next UIAbility主动更新卡片信息的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS 鸿蒙Next UIAbility主动更新卡片信息的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)系统中,UIAbility主动更新卡片信息通常涉及到与Ability生命周期管理、数据绑定以及卡片服务的交互。以下是实现这一功能的基本步骤概述:

  1. 确保卡片服务已注册:首先,确保你的应用已经正确注册了卡片服务,并且卡片服务能够正常接收和响应来自系统的请求。

  2. 使用DataAbility或ContentProvider:如果你的卡片信息来源于数据库或其他数据源,可以通过DataAbility或ContentProvider来提供数据访问接口。

  3. 在UIAbility中监听数据变化:利用数据绑定或观察者模式,在UIAbility中监听数据源的变化。一旦数据发生变化,立即触发卡片更新逻辑。

  4. 主动触发卡片更新:当检测到数据变化时,可以通过调用系统提供的API来主动触发卡片的更新。这通常涉及到与卡片服务的交互,以请求重新渲染卡片。

  5. 处理卡片更新回调:在卡片更新过程中,可能需要处理一些回调,如更新成功或失败的回调,以便进行相应的处理。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部