鸿蒙OS开发文档 鸿蒙OS 码生成开发指导

2024-02-25 开发教程 鸿蒙OS开发文档 匿名 1

场景介绍

码生成能够根据给定的字符串信息,生成相应的二维码图片。常见应用场景举例:

  • 社交或通讯类应用:根据输入的联系人信息,生成联系人二维码。
  • 购物或支付类应用:根据输入的支付链接,生成收款或付款二维码。

接口说明

码生成提供了的 IBarcodeDetector()接口,常用方法的功能描述如下:

接口名方法功能描述
IBarcodeDetectorint detect(String barcodeInput, byte[] bitmapOutput, int width, int height);根据给定的信息和二维码图片尺寸,生成二维码图片字节流。
IBarcodeDetectorint release();停止QR码生成服务,释放资源。

开发步骤

  1. 在使用码生成 SDK 时,需要先将相关的类添加至工程。
import ohos.cvinterface.common.ConnectionCallback;import ohos.cvinterface.common.VisionManager;import ohos.cvinterface.qrcode.IBarcodeDetector;
  1. 定义 ConnectionCallback 回调,实现连接能力引擎成功与否后的操作。
ConnectionCallback connectionCallback = new ConnectionCallback() {
@Override
public void onServiceConnect() {
// Do something when service connects successfully
}
@Override
public void onServiceDisconnect() {
// Do something when service connects unsuccessfully
}
};
  1. 调用 VisionManager.init() 方法,将此工程的 context 和 connectionCallback 作为入参,建立与能力引擎的连接,context 应为 ohos.aafwk.ability.Ability 或 ohos.aafwk.ability.AbilitySlice 的实例或子类实例。
int result = VisionManager.init(context, connectionCallback);
  1. 实例化 IBarcodeDetector 接口,将此工程的 context 作为入参。
IBarcodeDetector barcodeDetector = VisionManager.getBarcodeDetector(context);
  1. 定义码生成图像的尺寸,并根据图像大小分配字节流数组空间。
final int SAMPLE_LENGTH = 152;
byte[] byteArray = new byte[SAMPLE_LENGTH * SAMPLE_LENGTH * 4];
  1. 调用 IBarcodeDetector 的 detect() 方法,根据输入的字符串信息生成相应的二维码图片字节流。
int result = barcodeDetector.detect("This is a TestCase of IBarcodeDetector", byteArray, SAMPLE_LENGTH, SAMPLE_LENGTH);

如果返回值为 0,表明调用成功。

  1. 当码生成能力使用完毕后,调用 IBarcodeDetector 的 release() 方法,释放资源。
result = barcodeDetector.release();
  1. 调用 VisionManager.destroy() 方法,断开与能力引擎的连接。
VisionManager.destroy();