CN | EN

Developer Center

Home-Developer Center-Documentation

AI Weighing Recognition SDK (AAR) Integration Guide

Artifact: aiweight-sdk-debug.aar
Target projects: Android weighing checkout / weighing recognition applications
This document is intended for integrator developers. It describes how to import the AAR, the public interfaces, the bundled files and precautions.

Contents


1. Overview

1.1 Introduction

This AAR is a reusable SDK extracted from a weighing recognition application and provides three capabilities:

  1. Activation code verification: device ID generation, local offline activation code verification, activation time window decoding, local state persistence and protection against system time rollback; it also bundles an activation login page that can be launched directly.
  2. AI product recognition: loads the bundled AI model and returns candidate categories and similarity for an input product image; it also provides local sample image management and category recognition data loading and saving.
  3. Barcode scanning: bundles barcode localization, multi-engine decoding and local barcode product storage, and provides a scan page that can be launched directly; the scan page requires activation code verification before entry.
Note: This SDK does not include weighing serial ports, shopping cart, receipt printing, customer display or other business UI and checkout flows; these are still implemented by the integrator application.

1.2 Package Contents

CategoryContent
Activation codeActivation verification facade, result entity, bundled login page
Recognition codeRecognition facade, model processing wrapper, local sample image management, result entity
Barcode codeBarcode localization, image enhancement, multi-engine decoding, barcode product storage, scan overlay view, bundled scan page
Bundled AI modelsPackaged with the AAR; automatically extracted to the app internal directory and loaded on first launch
Bundled native runtimearm64-v8a runtime libraries packaged with the AAR

1.3 Environment

ItemRequirement
minSdkVersion25
compileSdkVersion33
Supported ABIarm64-v8a
Build environmentAndroid Gradle Plugin 7.2.0 / Gradle 7.3.3 and later compatible versions
Third-party dependenciesappcompat, gson, barcode decoding library (already declared in the AAR; integrators do not need to add them again)

2. Integration Steps

2.1 Import the AAR

  1. Copy aiweight-sdk-debug.aar into the integrator project's app/libs/ directory (create the directory if it does not exist).
  2. Add it to dependencies in the integrator's app/build.gradle:
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.aar'])
}

2.2 Repository and Dependency Confirmation

The AAR itself depends on androidx.appcompat:appcompat:1.6.1, com.google.code.gson:gson:2.10.1, as well as com.google.mlkit:barcode-scanning:17.2.0, com.google.zxing:core:3.5.2 and com.yanzhenjie.zbar:zbar:1.0.0 required for barcode decoding. The integrator project must be able to access the Google repository or a local cache:

repositories {
    google()
    mavenCentral()
}

2.3 Permission Declaration

Add the following permissions to the integrator's AndroidManifest.xml as needed (recognition and sample image read/write require storage permissions; the camera permission should be requested by the business UI itself):

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

2.4 Initialization

The SDK does not need to be forcibly initialized in the Application. Each facade class initializes automatically on first use; it is recommended to call the recognition facade once after the app starts and before entering the business UI to complete model loading.


3. Activation Code Module

3.1 Module Contents

ClassPackageDescription
ActivationManagercom.aiweight.sdk.activationActivation code verification facade, singleton entry
ActivationStatuscom.aiweight.sdk.activationVerification result / current status entity
ActivationLoginActivitycom.aiweight.sdk.activationBundled activation login page (optional)

3.2 ActivationManager Methods

Obtain the singleton via ActivationManager.get(Context).

MethodReturn valueDescription
get(Context context)ActivationManagerGet the singleton instance (static method)
getDeviceId()StringGet the unique device ID of the current device (bound to the activation code)
verify(String code)ActivationStatusVerify the entered activation code; on success writes it to the local cache and records the maximum historical time
getStatus()ActivationStatusRead the locally saved activation code and verify it again, for a silent check before entering protected screens
isActivated()booleanWhether the device is currently activated
decodeSpan(String code)StringDecode the start/end time, valid days and current status from the activation code without gate control judgment; returns null for an invalid format
clearActivation()voidClear the local activation code, time cache and saved device ID; a new device ID is generated on next launch

3.3 ActivationStatus Fields

FieldTypeDescription
activatedbooleanWhether verification passed (within the validity period, device matched, not invalidated by rollback)
deviceIdStringUnique device ID of the current device
startSeclongActivation window start time (second-level timestamp, GMT+8)
endSeclongActivation window end time (second-level timestamp, GMT+8)
validDayslongNumber of valid days
leftDayslongRemaining days (rounded up)
messageStringSuccess / failure message
spanTextStringMulti-line text describing the time span and status

3.4 Launching the Bundled Login Page

To use the SDK bundled page directly:

// 从业务页面跳转
ActivationLoginActivity.start(activity);

// 也可自行构造 Intent
Intent intent = new Intent(activity, ActivationLoginActivity.class);
activity.startActivity(intent);

After successful activation the page returns Activity.RESULT_OK; the integrator can call getStatus() in onActivityResult or after the page returns to verify again.

3.5 Usage Examples

Verify an activation code:

ActivationManager mgr = ActivationManager.get(this);
ActivationStatus status = mgr.verify(inputCode);

if (status.activated) {
    // 校验通过,可进入受保护功能
} else {
    // status.message 为失败原因,status.spanText 为时间窗口说明
    Toast.makeText(this, status.message, Toast.LENGTH_LONG).show();
}

Silent check before entering a screen:

if (!ActivationManager.get(this).isActivated()) {
    // 未激活,跳转登录页
    ActivationLoginActivity.start(this);
    return;
}

Decode and inspect the validity period:

String span = ActivationManager.get(this).decodeSpan(code);
// span 形如:
// 激活开始:2026-11-12 00:00:00
// 激活结束:2026-11-14 23:59:59
// 有效天数:3 天
// 当前状态:✅ 可激活,剩余 3 天

Reset / rebind:

ActivationManager.get(this).clearActivation();

3.6 Persistence

Storage nameKeyContent
device_configactivation_codeMost recently verified activation code
device_configdevice_id_v4Device ID generated and saved on this device
rollback_guardlast_max_wallMaximum system time ever recorded, used to prevent time rollback

Verification is performed entirely locally without network access; the device ID is bound one-to-one to the activation code, and the original activation code is unusable after changing devices.


4. AI Recognition Module

4.1 Module Contents

ClassPackageDescription
ClipHelpercom.aiweight.sdk.recognitionRecognition facade, singleton entry
clip.ClipInferenceWrappercom.aiweight.sdk.recognition.clipAI model processing wrapper (internal use, generally not called directly)
LocalImageManagercom.aiweight.sdk.recognitionLocal sample image saving, scanning, deletion and thumbnails
InferenceResultcom.aiweight.sdk.recognitionRecognition output container (internal use)

4.2 Initialization and Singleton

ClipHelper helper = ClipHelper.getInstance(context);
boolean ready = helper.isReady();
  • The first getInstance call loads the bundled AI model and reads the local category recognition data.
  • If model loading fails or the model is not ready, recognition methods return an empty list; call reloadModels() to retry.

4.3 Recognition Methods

MethodReturn valueDescription
clipClassifyTopN(Bitmap bitmap, int topN)List<TopResult>Return the top N candidate categories with the highest similarity
clipClassify(Bitmap bitmap)ResultReturn a single recognition result after stabilization
clipClassify(Bitmap bitmap, RectF location)ResultRecognize within the specified region
clipClassify(Bitmap bitmap, RectF location, int trackId)ResultRecognize with the specified region and tracking ID, with consecutive-frame stabilization
isReady()booleanWhether the AI model is ready
release()voidRelease model and cache resources; call when the app exits

4.4 Result Entity Fields

ClipHelper.TopResult / ClipHelper.Result

FieldTypeDescription
clsNameStringCandidate category name
scorefloatSimilarity (0~1, the higher the closer)
isNegativebooleanWhether it is an excluded category

4.5 Sample and Category Management Methods

MethodReturn valueDescription
getCategoryCount()intNumber of current positive sample categories
getExcludeList()List<String>List of excluded categories
isExclude(String label)booleanWhether the specified category is excluded
addTextCategory(String label, boolean isExclude, float[] feature)booleanAdd category recognition data to the in-memory cache
removeCategory(String label)booleanDelete the specified category and its data
toggleExcludeStatus(String label)booleanToggle a category between excluded / normal status
rebuildAllLocalFeatures()intRegenerate all category recognition data from local sample images
rebuildFeaturesFromLocalImages(List<String> labels)intRebuild recognition data for the specified category list
saveFeaturesToFile()booleanWrite the current category recognition data to a local file
loadCategoriesFromFiles()booleanLoad category recognition data from local files
refreshCategoriesFromFiles()voidRefresh the in-memory category data
forceReloadFeatures()booleanForce reload category recognition data
extractImageFeature(Bitmap bitmap)float[]Extract recognition reference data from a single image (for internal comparison)
getThreshold() / setThreshold(float)float / voidRead/write the similarity threshold

4.6 Local Sample Image Management LocalImageManager

MethodReturn valueDescription
LocalImageManager(Context)ConstructorInitialize the local sample directory
saveImage(Bitmap bitmap, String label)StringSave a sample image to the specified category directory and return the file path
getAllImages()List<LocalImageItem>Scan all local sample images
getImagesByLabel(String label)List<LocalImageItem>Get sample images by category
getLabelCounts()Map<String, Integer>Sample count statistics for each category
deleteImage(String filePath)booleanDelete the specified sample image
getThumbnail(String filePath)BitmapRead the sample thumbnail
getImage(String filePath)BitmapRead the original sample image

LocalImageItem fields: filePath, filename, label, size, lastModified, thumbnailPath, isSelected.

4.7 Usage Examples

Get candidates for a single image:

ClipHelper helper = ClipHelper.getInstance(this);
List<ClipHelper.TopResult> candidates = helper.clipClassifyTopN(bitmap, 3);

for (ClipHelper.TopResult item : candidates) {
    // item.clsName  类别名称
    // item.score    相似度
}

Save a sample image and rebuild category data:

LocalImageManager manager = new LocalImageManager(this);
String path = manager.saveImage(bitmap, "绿色草莓");

ClipHelper helper = ClipHelper.getInstance(this);
helper.rebuildAllLocalFeatures();
helper.saveFeaturesToFile();

Release resources:

@Override
protected void onDestroy() {
    super.onDestroy();
    ClipHelper.getInstance(this).release();
}

5. Barcode Scanning Module

5.1 Module Contents

ClassPackageDescription
BarcodeScanActivitycom.aiweight.sdk.recognition.barcodeBundled scan page (camera preview + localization + decoding + result callback)
BarcodeDecodercom.aiweight.sdk.recognition.barcodeMulti-engine decoder (Bitmap / NV21 / grayscale frames)
BarcodeYoloDetectorcom.aiweight.sdk.recognition.barcodeBarcode / QR code localization wrapper
BarcodeSrDetectorcom.aiweight.sdk.recognition.barcodeBarcode grayscale image enhancement wrapper
BarcodeProductStorecom.aiweight.sdk.recognition.barcodeLocal barcode product storage
ScanOverlayViewcom.aiweight.sdk.recognition.barcodeScan preview overlay view (used by the bundled page)

5.2 Launching the Bundled Scan Page (Recommended)

Launch it with the Activity Result API:

private final ActivityResultLauncher<Intent> mScanLauncher =
        registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                        String code = result.getData()
                                .getStringExtra(BarcodeScanActivity.EXTRA_RESULT);
                        if (code != null && !code.isEmpty()) {
                            // code 为归一化后的 EAN-13 条码
                        }
                    }
                });

// 调起扫码页
mScanLauncher.launch(new Intent(this, BarcodeScanActivity.class));
  • After successful recognition the page returns Activity.RESULT_OK and passes the barcode back through EXTRA_RESULT; canceling or returning directly passes nothing back.
  • The scan page entry already includes activation gate control: when activation code verification has not passed, the page closes directly and scanning is not entered.

5.3 Decoder BarcodeDecoder

Construction: new BarcodeDecoder().

MethodReturn valueDescription
decodeFromBitmap(Bitmap bmp)DecodeResultDecode the passed Bitmap
decodeNv21(byte[] nv21, int w, int h, int rotation)DecodeResultDecode a full NV21 frame
decodeNv21Region(byte[] nv21, int w, int h, int left, int top, int rw, int rh, int rotation)DecodeResultDecode the specified region
decodeZxingNv21Region(...)DecodeResultDecode the specified region with the backup decoder
decodeZBarNv21Region(...)DecodeResultDecode the specified region with the preferred decoder
decodeGray(byte[] gray, int w, int h)DecodeResultDecode a grayscale frame (enhanced output)
decodeZBarGray(byte[] gray, int w, int h)DecodeResultDecode a grayscale frame with the preferred decoder
setCropRatio(float) / getCropRatio()void / floatCenter region crop scale ratio

BarcodeDecoder.DecodeResult Fields

FieldTypeDescription
textStringDecoded barcode content
boundingBoxRectPosition box of the barcode in the original image
cornerPointsPoint[]Four corner coordinates of the barcode
imageWidthintOriginal image width
imageHeightintOriginal image height
sourceStringDecoding source (identifies which engine decoded it)

5.4 Localization and Image Enhancement Wrappers

BarcodeYoloDetector

MethodReturn valueDescription
init(String modelPath)booleanLoad the localization model and initialize
isReady()booleanWhether it is ready
detect(byte[] nv21, int w, int h)float[]Localize an NV21 frame and return the detection box array; returns an empty array when not ready
deinit()voidRelease the localization model

BarcodeSrDetector

MethodReturn valueDescription
init(String modelPath)booleanLoad the enhancement model and initialize
isReady()booleanWhether it is ready
upscale(byte[] gray, int inW, int inH)byte[]Apply 2x enhancement to the grayscale of the box region and return the enhanced grayscale frame
deinit()voidRelease the enhancement model

5.5 Barcode Product Store BarcodeProductStore

MethodReturn valueDescription
BarcodeProductStore(Context)ConstructorOpen the local product store
save(String barcode, String name, float price, String unit)voidCreate a record; unit is UNIT_PCS (by piece) or UNIT_KG (by weight)
get(String barcode)ItemGet a product record; returns null if it does not exist
exists(String barcode)booleanWhether a record already exists
remove(String barcode)voidDelete a record
getAll()Map<String, Item>All records
normalize(String code)StringStatic method; remove non-alphanumeric characters and left-pad EAN-13 to 13 digits

BarcodeProductStore.Item Fields: barcode, name, price, unit; the isByPcs() method determines whether pricing is by piece.

5.6 Usage Example: Look Up a Product After Scanning a Barcode

BarcodeProductStore store = new BarcodeProductStore(this);
BarcodeProductStore.Item item = store.get(code);
if (item != null) {
    // item.name  商品名称
    // item.price 单价
    // item.unit  计价单位
} else {
    // 未建档,可引导用户绑定条码商品
}

6. Bundled Files

6.1 Bundled AI Models

FileLocation (inside the AAR)Description
clip_vision_finetuned.rknnassets/AI model for product image recognition
barcode_det.rknnassets/AI model for barcode / QR code localization
Models are packaged with the AAR. On the app's first launch the SDK automatically extracts them to the app internal cache directory and loads them; integrators do not need to copy them manually.

6.2 Bundled Native Runtime (arm64-v8a)

FileLocation (inside the AAR at jni/arm64-v8a/)Description
librknn4j.soJava bridge library for model processing
librknnrt.soRuntime support library for model processing
libbarcodeyolo.soNative library for barcode localization
libbarcodesr.soNative library for barcode image enhancement

6.3 Local Storage Directories

PathContent
filesDir/text_features.binCategory recognition data (binary)
filesDir/categories.jsonCategory and exclusion mapping
外部文件目录/样本图片目录/images/<类别名>/Original local sample images
外部文件目录/样本图片目录/thumbnails/<类别名>/Sample thumbnails

7. Precautions and FAQ

  1. ABI restriction: The bundled native libraries only provide arm64-v8a. Do not run recognition or scanning features on devices with other CPU architectures.
  2. First-load duration: Loading the AI model for the first time takes some time. It is recommended to complete initialization before entering the checkout UI; returning empty results from recognition / scanning APIs during loading is normal.
  3. Threading requirements: Do not perform time-consuming recognition or decoding calls on the main thread; process consecutive frames on a worker thread.
  4. Resource release: When the app exits or the recognition feature is no longer used, call the release method of the corresponding facade to free models and caches; the scan page automatically releases the localization and enhancement models in onDestroy.
  5. External model override: If a model file with the same name is placed in /sdcard/DoubaoClip/, the SDK loads the external file first, so the model can be replaced without repackaging.
  6. Activation gate control: The bundled scan page automatically verifies the activation code before entry and closes directly when not activated; for other features such as AI recognition, the business side should call ActivationManager.isActivated() to complete the check before entering the screen.
  7. Barcode enhancement model: The barcode image enhancement (super-resolution) model is currently not bundled in the AAR; when it is missing, the enhancement wrapper is unavailable, which does not affect barcode localization and regular decoding. To enable it, place a model file with the same name in the same path as described in 6.1.
  8. Time accuracy: Activation verification relies on the device system time. If the device time is manually rolled back or adjusted outside the validity period, verification will fail; keep the device time accurate.

8. Class and Package Reference

Public classFull package namePurpose
ActivationManagercom.aiweight.sdk.activation.ActivationManagerActivation code verification facade
ActivationStatuscom.aiweight.sdk.activation.ActivationStatusActivation result / status entity
ActivationLoginActivitycom.aiweight.sdk.activation.ActivationLoginActivityBundled activation login page
ClipHelpercom.aiweight.sdk.recognition.ClipHelperAI recognition facade
LocalImageManagercom.aiweight.sdk.recognition.LocalImageManagerLocal sample image management
InferenceResultcom.aiweight.sdk.recognition.InferenceResultRecognition output container
ClipInferenceWrappercom.aiweight.sdk.recognition.clip.ClipInferenceWrapperModel processing wrapper (internal)
BarcodeScanActivitycom.aiweight.sdk.recognition.barcode.BarcodeScanActivityBundled barcode scan page
BarcodeDecodercom.aiweight.sdk.recognition.barcode.BarcodeDecoderMulti-engine barcode decoder
BarcodeYoloDetectorcom.aiweight.sdk.recognition.barcode.BarcodeYoloDetectorBarcode / QR code localization wrapper
BarcodeSrDetectorcom.aiweight.sdk.recognition.barcode.BarcodeSrDetectorBarcode grayscale image enhancement wrapper
BarcodeProductStorecom.aiweight.sdk.recognition.barcode.BarcodeProductStoreLocal barcode product storage
ScanOverlayViewcom.aiweight.sdk.recognition.barcode.ScanOverlayViewScan preview overlay view

Appendix: Artifacts and Build

ItemDescription
Debug artifactaiweight-sdk/build/outputs/aar/aiweight-sdk-debug.aar
Release build command./gradlew :aiweight-sdk:assembleRelease
Module source directoryaiweight-sdk/src/main/
Module build scriptaiweight-sdk/build.gradle