快速开始

本文介绍如何将蚂蚁动态卡片组件接入到 HarmonyOS NEXT 客户端。您可以基于已有工程使用 ohpmrc 方式接入蚂蚁动态卡片 SDK 到客户端。

前置条件

添加蚂蚁动态卡片 SDK 前,请您确保已经将工程接入到 mPaaS。

更多信息请参见开发指南 接入 mPaaS 能力

引入依赖

在项目的 .ohpmrc 文件中添加如下代码仓库。

@mpaas:registry=https://mpaas-ohpm.oss-cn-hangzhou.aliyuncs.com/meta

添加 SDK

通过 使用 mppm 工具 安装小程序组件。

image.jpeg

配置权限

module.json5 中配置所需权限。

"requestPermissions":[
  {
  "name" : "ohos.permission.GET_NETWORK_INFO",
  },
  {
  "name" : "ohos.permission.INTERNET",
  }
]

使用 SDK

初始化卡片引擎

if (!CubeEngine.getInstance().peekIsInit()) {
    let config = CubeEngineConfig.obtain().setEnableDebugPath(true)
    CubeEngine.getInstance().init(config);
}

代码示例

创建卡片

aboutToAppear() {
  CubeEngine.getInstance().createCard(
    CubeCardConfig
      .obtain()
      .setTemplateId(this.cardId)
      .setWidth(CKSystemInfo.getDisplayMetricsWidth())
      .setVersion(this.cardVer)
      .setData(this.dataString)
    ,
    {
      onLoaded: (card: CubeCard | null, cardType: CCardType, config: CubeCardConfig, code: CubeCardResultCode) => {
        if (CubeCardResultCode.CubeCardResultSucc == code) {
          this.instance = card;
        }
      }
    });
}

build() {
  Stack() {
    Column() {
      if (this.instance) {
        CubeCardComponent({ instance: this.instance })
      }
    }
    .justifyContent(FlexAlign.Start)
  }
}

销毁卡片

aboutToDisappear() {
  if (this.instance) {
    this.instance.destroy();
  }
}

预置卡片

预置卡片需要在初始化卡片引擎时设置,目前支持两种设置方式。

  • 单独设置某个文件夹,该文件夹在 resources/rawfile 下。

    .setResourcePath("mp")
  • 设置多个文件夹,文件夹在 resources/rawfile 下。

    let resourcePaths: Array<string> = ["cube", "smart", "mp"]
    .setResourcePaths(resourcePaths)

    此时完整的初始化代码如下所示。

    let resourcePaths: Array<string> = ["cube", "smart", "mp"]
    let config = CubeEngineConfig.obtain().setEnableDebugPath(true)
      .setResourcePath("mp")
      .setResourcePaths(resourcePaths)
    CubeEngine.getInstance().init(config);

自定义组件

  1. 创建自定义组件,代码示例如下。

    @Builder
    export function buildMyCustomComponent(builder: ComponentBuilder) {
      MyCustomComponent({
        node: builder.node,
        cardInstance: builder.cardInstance
      })
    }
    
    @Component
    export struct MyCustomComponent {
      @State
      node: CKNode = new CKNode();
      @State
      cardInstance: CubeCard | null = null;
      @State
      text: string = ""
    
      aboutToAppear(): void {
        if (this.node) {
          this.node.component = this;
          this.updateWidgetData()
          this.node.onChange = (type: NodeChangeType, changeNode: CKNode, childNode: CKNode | null) => {
            this.updateWidgetData()
          };
        }
      }
    
      build() {
        if (this.node) {
          Column() {
            Text("我是原生组件,点我通知卡片事件回调,"+this.text).onClick((event) => {
              let args: Record<string, object> = {}
              args["p1"] = "widget:" + systemDateTime.getTime() as ESObject
              CWidgetApi.getInstance().sendEventToJS(this.node, 'on-WidgetToCube', args)
            })
          }
          .width(this.node.size.width)
          .height(this.node.size.height)
          .position(this.node.position)
        }
      }
    
      updateWidgetData(): void {
        this.text = this.node.attributes.get("value") as string
      }
    
      public cubeToWidget(instance: FalconInstance, args: object, func: IFalconCallback): void {
        this.text = "接收到卡片调用自定义方法,参数:"+JSON.stringify(args)
        func.invoke("cubeToWidget callback data: " + systemDateTime.getTime())
      }
    }
  2. 注册自定义组件。

    自定义组件需要在初始化卡片引擎时进行注册,注册代码如下。

    let customBuilder: WrappedBuilder<[ComponentBuilder]> = wrapBuilder(buildMyCustomComponent)
    let customWidgetInfo: CWidgetInfo = new CWidgetInfo("custom-widget", customBuilder)
    CubeEngine.getInstance().registerWidgets([customWidgetInfo])

卡片调用客户端方法

  1. 创建自定义 module。

    export class NativeCubeModule implements IFalconModule {
      getName(): string {
        return "mpaas_demo_cube2native";
      }
    
      cubeToClient(instance: FalconInstance, params: object, callback: IFalconCallback) {
        hilog.debug(0x0000, `cubeToClient: ${params}`, '');
        promptAction.showToast({
          message: JSON.stringify(params)
        })
        callback.invoke("cubeToClient callback data: " + systemDateTime.getTime())
      }
    }
  2. 注册自定义 module。

    CubeEngine.getInstance().registerModule(new MpaasJsapiModule(),new MriverJsapiModule(),  new NativeCubeModule())
    说明
    • MriverJsapiModule 可以使用 RPC、HttpRequest、Request 等方法。

    • MpaasJsapiModule 可以使用 addNotifyListener、removeNotifyListener、postNotification 等方法。