Getting started

Updated at:

This topic describes how to integrate the Ant Dynamic Card component into a HarmonyOS NEXT client. You can use the ohpmrc method to add the Ant Dynamic Card software development kit (SDK) to your existing project.

Prerequisites

Before you add the Ant Dynamic Card SDK, make sure that you have integrated your project with mPaaS.

For more information, see Integrate with mPaaS.

Import dependencies

Add the following code repository to the .ohpmrc file of your project.

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

Add the SDK

You can install the dynamic card component by using the mppm tool.

Configure permissions

Configure the required permissions in the module.json5 file.

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

Use the SDK

Initialize the card engine

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

Code example

Create a card

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)
  }
}

Destroy a card

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

Preset Cards

You need to set preset cards during the initialization of the card engine. Two methods are currently supported.

  • Set a single folder in the resources/rawfile directory.

    .setResourcePath("mp")
  • Set multiple folders in the resources/rawfile directory.

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

    The complete initialization code is as follows.

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

Custom Components

  1. Create a custom component. The following code provides an example.

    @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("I am a native component. Click me to notify the card of the event callback, "+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 = "Received a custom method call from the card. Parameters: "+JSON.stringify(args)
        func.invoke("cubeToWidget callback data: " + systemDateTime.getTime())
      }
    }
  2. Register the custom component.

    Add the registration code during the initialization of the card engine. The following code provides an example.

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

Calling a client method from a card

  1. Create a custom 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. Register the custom module.

    CubeEngine.getInstance().registerModule(new MpaasJsapiModule(),new MriverJsapiModule(),  new NativeCubeModule())
    Note
    • MriverJsapiModule supports methods such as RPC, HttpRequest, and Request.

    • MpaasJsapiModule supports methods such as addNotifyListener, removeNotifyListener, and postNotification.