HarmonyOS鸿蒙Next中如何实现在应用一键添加卡片功能,而不是通过拉起卡片管理页面添加卡片

HarmonyOS鸿蒙Next中如何实现在应用一键添加卡片功能,而不是通过拉起卡片管理页面添加卡片 如何实现在应用一键添加卡片功能,而不是通过拉起卡片管理页面添加卡片。目前应用需要实现该功能,但未找到相关接口和文档?如视频所示

Video


更多关于HarmonyOS鸿蒙Next中如何实现在应用一键添加卡片功能,而不是通过拉起卡片管理页面添加卡片的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复

开发者您好,

【解决方案】

通过bindsheet拉起半模态弹窗,使用AddFormMenuItem添加卡片。

1.创建应用内预览展示以及卡片中实际展示的页面。由于该页面需要在应用内及卡片复用,所以采用HAR包的形式创建。参考开发静态共享包,新建一个名称为myCard的空白HAR包。分别在src/main/ets/components目录下创建MyCardOne.ets和MyCardTwo.ets文件,开发对应的卡片页面。

// src/main/ets/components/MyCardOne.ets
@Preview
@Component
export struct MyCardOne {
  build() {
    Row() {
      Text('这里是第一张卡片');
      Image($r('sys.media.clone_app_badge_1'))
        .width(60);
    }
    .padding(16)
    .justifyContent(FlexAlign.SpaceBetween)
    .width('100%')
    .height('100%');
  }
}
// src/main/ets/components/MyCardTwo.ets
@Preview
@Component
export struct MyCardTwo {
  build() {
    Row() {
      Image($r('sys.media.AI_circle_viewfinder'))
        .width(60);
      Text('这里是第二张卡片');
    }
    .padding(16)
    .justifyContent(FlexAlign.SpaceBetween)
    .width('100%')
    .height('100%');
  }
}

2.在HAR包src/main/ets/enums目录下定义CardStyle类,定义三种卡片样式状态。

export enum CardStyle {
  DEFAULT, // 默认样式
  ONE, // 第一种卡片样式
  TWO // 第二种卡片样式
}

3.在HAR包Index.ets文件中导出卡片样式以及枚举类。

export { MainPage } from './src/main/ets/components/MainPage';

export { MyCardOne } from './src/main/ets/components/MyCardOne';

export { MyCardTwo } from './src/main/ets/components/MyCardTwo';

export { CardStyle } from './src/main/ets/enums/CardStyle';

4.在entry模块中,参考引用及管理共享包,在oh-package.json5中配置对HAR包的引用。

{
  "name": "entry",
  "version": "1.0.0",
  "description": "Please describe the basic information.",
  "main": "",
  "author": "",
  "license": "",
  "dependencies": {
    "mycard": "file:../myCard"
  }
}

5.参考创建ArkTS卡片创建默认卡片,卡片展示的内容根据@LocalStorageProp(‘style’)状态变量动态展示。WidgetCard.ets中定义如下:

import { CardStyle, MyCardOne, MyCardTwo } from 'mycard';

const local = new LocalStorage();

@Entry(local)
@Component
export struct WidgetCard {
  // 设置卡片样式
  @LocalStorageProp('style') style: CardStyle = CardStyle.DEFAULT;

  build() {
    Row() {
      if (this.style == CardStyle.DEFAULT) {
        this.default();
      } else if (this.style == CardStyle.ONE) {
        MyCardOne();
      } else if (this.style == CardStyle.TWO) {
        MyCardTwo();
      }
    }
    .width('100%')
    .height('100%');
  }

  // 默认的卡片效果
  @Builder
  default() {
    Row() {
      Text('初始化默认卡片');
    }
    .backgroundImage($r('app.media.startIcon'))
    .backgroundImageSize({ width: '100%', height: '100%' })
    .width('100%')
    .height('100%');
  }
}

6.在主应用中定义半模态面板,预览卡片内容,使用AddFormMenuItem组件将预览内容直接添加至桌面。Index.ets示例代码为:

//  index.ets
import { AddFormMenuItem, PromptAction } from '@kit.ArkUI';
import { formBindingData } from '@kit.FormKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { CardStyle, MyCardOne, MyCardTwo } from 'mycard';
import { BusinessError } from '@kit.BasicServicesKit';

const tag = 'AddFormMenuItem';

@Entry
@Component
struct Index {
  // 标识半模态弹窗弹出的状态
  @State isShowOne: boolean = false;
  @State isShowTwo: boolean = false;
  // 组件标识id
  private compId: string = 'addforms@xxx';
  // 应用内弹窗
  promptAction: PromptAction = this.getUIContext().getPromptAction();

  @Builder
  MyMenu(style: CardStyle) {
    Menu() {
      AddFormMenuItem(
        {
          // 设置为应用包名
          bundleName: 'com.example.myapplication',
          abilityName: 'EntryFormAbility', // 模块ability名称
          parameters: {
            'ohos.extra.param.key.form_dimension': 3, // 卡片尺寸,1代表1*2卡片,2代表2*2卡片,3代表2*4卡片,4代表4*4卡片,7代表6*4卡片
            'ohos.extra.param.key.form_name': 'widget', // 卡片名称
            'ohos.extra.param.key.module_name': 'entry' // 卡片所属的模块名称
          },
        },
        this.compId,
        {
          formBindingData: formBindingData.createFormBindingData({ style: style }),
          callback: (error, formId) => {
            hilog.info(0x3900, tag, `callback info:error = ${JSON.stringify(error)}, formId = ${formId}`);
            if (error?.code === 0) {
              try {
                this.promptAction.showToast({
                  message: "添加至桌面成功",
                  duration: 2000
                });
              } catch (error) {
                let message = (error as BusinessError).message;
                let code = (error as BusinessError).code;
                console.error(`showToast args error code is ${code}, message is ${message}`);
              }
              ;

            } else {
              try {
                this.promptAction.showToast({
                  message: "添加至桌面失败,请尝试其它添加方式",
                  duration: 2000
                });
              } catch (error) {
                let message = (error as BusinessError).message;
                let code = (error as BusinessError).code;
                console.error(`showToast args error code is ${code}, message is ${message}`);
              }
              ;
            }
            if (style == CardStyle.ONE) {
              this.isShowOne = false;
            } else if (style == CardStyle.TWO) {
              this.isShowTwo = false;
            }
          },
          style: {
            options: {
              content: " ", // 菜单内容,可以自己提供。默认使用"sys.string.ohos_add_form_to_desktop"
            }
          }
        }
      );
    };
  }

  @Builder
  myBuilder(style: CardStyle) {
    Column() {
      Text('卡片预览效果图')
        .fontSize(26);
      // 卡片内容
      Row() {
        if (style == CardStyle.ONE) {
          MyCardOne();
        } else if (style == CardStyle.TWO) {
          MyCardTwo();
        }
      }
      .id(this.compId)
      .borderRadius(12)
      .backgroundColor(Color.White)
      // 2*2类型卡片的尺寸
      .width(300)
      .height(140);

      Row() {
        Stack() {
          Text('取消')
            .onClick(() => {
              if (style == CardStyle.ONE) {
                this.isShowOne = false;
              } else if (style == CardStyle.TWO) {
                this.isShowTwo = false;
              }
            });
        }.layoutWeight(1);

        Stack() {
          Text('添加')
            .fontColor(Color.Blue);
          this.MyMenu(style);
        }.layoutWeight(1);

      };
    }
    .padding({ top: 10 })
    .justifyContent(FlexAlign.SpaceBetween)
    .width('100%')
    .height('100%');
  }

  build() {
    Row() {
      Column({ space: 10 }) {
        Button('预览卡片一').onClick(() => {
          this.isShowOne = true;
        })
          .bindSheet($$this.isShowOne, this.myBuilder(CardStyle.ONE), {
            height: 300,
            backgroundColor: Color.Gray,
            preferType: SheetType.BOTTOM,
            showClose: false
          });

        Button('预览卡片二').onClick(() => {
          this.isShowTwo = true;
        })
          .bindSheet($$this.isShowTwo, this.myBuilder(CardStyle.TWO), {
            height: 300,
            backgroundColor: Color.Gray,
            preferType: SheetType.BOTTOM,
            showClose: false
          });
      }
      .width('100%');
    }
    .height('100%');
  }
}

【背景知识】

  • Form Kit(卡片开发服务)提供了一种在桌面、锁屏等系统应用上嵌入显示应用信息的开发框架和API,可以将应用内用户关注的重要信息或常用操作抽取到服务卡片(简称“卡片”)上,通过将卡片添加到桌面、锁屏等系统应用上,以达到信息展示、服务直达的便捷体验效果。
  • FormMenu组件封装了一个“添加至桌面”菜单,用于实现应用内长按组件生成“添加至桌面”菜单,点击该菜单,触发卡片添加至桌面操作。通过桌面访问该应用快捷卡片,可以直接访问该组件功能。在应用使用过程中,该组件作为留存和复访入口,可吸引用户将功能快捷添加到桌面。

更多关于HarmonyOS鸿蒙Next中如何实现在应用一键添加卡片功能,而不是通过拉起卡片管理页面添加卡片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


尊敬的开发者,您好!您的问题已受理,请您耐心等待,感谢您的理解与支持!

在HarmonyOS Next中,应用可通过FormExtensionAbility实现一键添加卡片。开发者需在module.json5中配置extensionAbilities,声明typeform,并在metadata中指定卡片信息。应用内调用formProvideracquireForm方法,传入卡片ID和尺寸,系统将直接添加卡片到桌面,无需跳转卡片管理页面。

在HarmonyOS Next中,实现应用内一键添加卡片到桌面的功能,核心是使用FormManageraddForm接口。该接口允许应用在不拉起系统卡片管理页面的情况下,直接将指定卡片添加到桌面。

关键步骤如下:

  1. 权限申请:在module.json5文件中声明ohos.permission.REQUIRE_FORM权限。

    "requestPermissions": [
      {
        "name": "ohos.permission.REQUIRE_FORM"
      }
    ]
    
  2. 获取FormManager实例:通过formManager模块的getFormManager方法获取。

    import { formManager } from '@kit.FormKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    let formMgr: formManager.FormManager = formManager.getFormManager();
    
  3. 调用addForm方法:这是实现一键添加的核心。你需要提供卡片的bundleNameabilityNameformName(在module.json5中定义的卡片标识),以及一个formInfo对象(通常包含dimension等信息)。

    let formInfo: formManager.FormInfo = {
      dimension: formManager.FormDimension.Dimension_2_2 // 示例:2x2卡片
    };
    try {
      let formId: string = await formMgr.addForm('your_bundleName', 'your_abilityName', 'your_formName', formInfo);
      // formId 是添加成功后返回的卡片唯一标识
      console.info(`Add form success, formId: ${formId}`);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Failed to add form. Code: ${err.code}, message: ${err.message}`);
    }
    

注意事项

  • addForm是一个异步接口,需要使用awaitPromise处理。
  • 调用此接口会触发系统弹窗,请求用户确认是否允许添加卡片到桌面。用户同意后,卡片才会被添加到桌面。
  • 确保传入的bundleNameabilityNameformName与卡片配置完全一致。
  • 此功能依赖于系统对卡片添加流程的支持,请确保在支持的设备及系统版本上使用。

通过以上步骤,即可在你的应用内实现一个按钮或操作,用户点击后直接弹出确认框,确认后卡片即刻添加到桌面,无需跳转到卡片中心页面。

回到顶部