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
- 2. Integration Steps
- 3. Activation Code Module
- 4. AI Recognition Module
- 5. Barcode Scanning Module
- 6. Bundled Files
- 7. Precautions and FAQ
- 8. Class and Package Reference
1. Overview
1.1 Introduction
This AAR is a reusable SDK extracted from a weighing recognition application and provides three capabilities:
- 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.
- 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.
- 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
| Category | Content |
|---|---|
| Activation code | Activation verification facade, result entity, bundled login page |
| Recognition code | Recognition facade, model processing wrapper, local sample image management, result entity |
| Barcode code | Barcode localization, image enhancement, multi-engine decoding, barcode product storage, scan overlay view, bundled scan page |
| Bundled AI models | Packaged with the AAR; automatically extracted to the app internal directory and loaded on first launch |
| Bundled native runtime | arm64-v8a runtime libraries packaged with the AAR |
1.3 Environment
| Item | Requirement |
|---|---|
| minSdkVersion | 25 |
| compileSdkVersion | 33 |
| Supported ABI | arm64-v8a |
| Build environment | Android Gradle Plugin 7.2.0 / Gradle 7.3.3 and later compatible versions |
| Third-party dependencies | appcompat, 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
- Copy
aiweight-sdk-debug.aarinto the integrator project'sapp/libs/directory (create the directory if it does not exist). - Add it to
dependenciesin the integrator'sapp/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
| Class | Package | Description |
|---|---|---|
ActivationManager | com.aiweight.sdk.activation | Activation code verification facade, singleton entry |
ActivationStatus | com.aiweight.sdk.activation | Verification result / current status entity |
ActivationLoginActivity | com.aiweight.sdk.activation | Bundled activation login page (optional) |
3.2 ActivationManager Methods
Obtain the singleton via ActivationManager.get(Context).
| Method | Return value | Description |
|---|---|---|
get(Context context) | ActivationManager | Get the singleton instance (static method) |
getDeviceId() | String | Get the unique device ID of the current device (bound to the activation code) |
verify(String code) | ActivationStatus | Verify the entered activation code; on success writes it to the local cache and records the maximum historical time |
getStatus() | ActivationStatus | Read the locally saved activation code and verify it again, for a silent check before entering protected screens |
isActivated() | boolean | Whether the device is currently activated |
decodeSpan(String code) | String | Decode the start/end time, valid days and current status from the activation code without gate control judgment; returns null for an invalid format |
clearActivation() | void | Clear the local activation code, time cache and saved device ID; a new device ID is generated on next launch |
3.3 ActivationStatus Fields
| Field | Type | Description |
|---|---|---|
activated | boolean | Whether verification passed (within the validity period, device matched, not invalidated by rollback) |
deviceId | String | Unique device ID of the current device |
startSec | long | Activation window start time (second-level timestamp, GMT+8) |
endSec | long | Activation window end time (second-level timestamp, GMT+8) |
validDays | long | Number of valid days |
leftDays | long | Remaining days (rounded up) |
message | String | Success / failure message |
spanText | String | Multi-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 name | Key | Content |
|---|---|---|
device_config | activation_code | Most recently verified activation code |
device_config | device_id_v4 | Device ID generated and saved on this device |
rollback_guard | last_max_wall | Maximum 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
| Class | Package | Description |
|---|---|---|
ClipHelper | com.aiweight.sdk.recognition | Recognition facade, singleton entry |
clip.ClipInferenceWrapper | com.aiweight.sdk.recognition.clip | AI model processing wrapper (internal use, generally not called directly) |
LocalImageManager | com.aiweight.sdk.recognition | Local sample image saving, scanning, deletion and thumbnails |
InferenceResult | com.aiweight.sdk.recognition | Recognition output container (internal use) |
4.2 Initialization and Singleton
ClipHelper helper = ClipHelper.getInstance(context);
boolean ready = helper.isReady();- The first
getInstancecall 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
| Method | Return value | Description |
|---|---|---|
clipClassifyTopN(Bitmap bitmap, int topN) | List<TopResult> | Return the top N candidate categories with the highest similarity |
clipClassify(Bitmap bitmap) | Result | Return a single recognition result after stabilization |
clipClassify(Bitmap bitmap, RectF location) | Result | Recognize within the specified region |
clipClassify(Bitmap bitmap, RectF location, int trackId) | Result | Recognize with the specified region and tracking ID, with consecutive-frame stabilization |
isReady() | boolean | Whether the AI model is ready |
release() | void | Release model and cache resources; call when the app exits |
4.4 Result Entity Fields
ClipHelper.TopResult / ClipHelper.Result
| Field | Type | Description |
|---|---|---|
clsName | String | Candidate category name |
score | float | Similarity (0~1, the higher the closer) |
isNegative | boolean | Whether it is an excluded category |
4.5 Sample and Category Management Methods
| Method | Return value | Description |
|---|---|---|
getCategoryCount() | int | Number of current positive sample categories |
getExcludeList() | List<String> | List of excluded categories |
isExclude(String label) | boolean | Whether the specified category is excluded |
addTextCategory(String label, boolean isExclude, float[] feature) | boolean | Add category recognition data to the in-memory cache |
removeCategory(String label) | boolean | Delete the specified category and its data |
toggleExcludeStatus(String label) | boolean | Toggle a category between excluded / normal status |
rebuildAllLocalFeatures() | int | Regenerate all category recognition data from local sample images |
rebuildFeaturesFromLocalImages(List<String> labels) | int | Rebuild recognition data for the specified category list |
saveFeaturesToFile() | boolean | Write the current category recognition data to a local file |
loadCategoriesFromFiles() | boolean | Load category recognition data from local files |
refreshCategoriesFromFiles() | void | Refresh the in-memory category data |
forceReloadFeatures() | boolean | Force reload category recognition data |
extractImageFeature(Bitmap bitmap) | float[] | Extract recognition reference data from a single image (for internal comparison) |
getThreshold() / setThreshold(float) | float / void | Read/write the similarity threshold |
4.6 Local Sample Image Management LocalImageManager
| Method | Return value | Description |
|---|---|---|
LocalImageManager(Context) | Constructor | Initialize the local sample directory |
saveImage(Bitmap bitmap, String label) | String | Save 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) | boolean | Delete the specified sample image |
getThumbnail(String filePath) | Bitmap | Read the sample thumbnail |
getImage(String filePath) | Bitmap | Read 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
| Class | Package | Description |
|---|---|---|
BarcodeScanActivity | com.aiweight.sdk.recognition.barcode | Bundled scan page (camera preview + localization + decoding + result callback) |
BarcodeDecoder | com.aiweight.sdk.recognition.barcode | Multi-engine decoder (Bitmap / NV21 / grayscale frames) |
BarcodeYoloDetector | com.aiweight.sdk.recognition.barcode | Barcode / QR code localization wrapper |
BarcodeSrDetector | com.aiweight.sdk.recognition.barcode | Barcode grayscale image enhancement wrapper |
BarcodeProductStore | com.aiweight.sdk.recognition.barcode | Local barcode product storage |
ScanOverlayView | com.aiweight.sdk.recognition.barcode | Scan 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_OKand passes the barcode back throughEXTRA_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().
| Method | Return value | Description |
|---|---|---|
decodeFromBitmap(Bitmap bmp) | DecodeResult | Decode the passed Bitmap |
decodeNv21(byte[] nv21, int w, int h, int rotation) | DecodeResult | Decode a full NV21 frame |
decodeNv21Region(byte[] nv21, int w, int h, int left, int top, int rw, int rh, int rotation) | DecodeResult | Decode the specified region |
decodeZxingNv21Region(...) | DecodeResult | Decode the specified region with the backup decoder |
decodeZBarNv21Region(...) | DecodeResult | Decode the specified region with the preferred decoder |
decodeGray(byte[] gray, int w, int h) | DecodeResult | Decode a grayscale frame (enhanced output) |
decodeZBarGray(byte[] gray, int w, int h) | DecodeResult | Decode a grayscale frame with the preferred decoder |
setCropRatio(float) / getCropRatio() | void / float | Center region crop scale ratio |
BarcodeDecoder.DecodeResult Fields
| Field | Type | Description |
|---|---|---|
text | String | Decoded barcode content |
boundingBox | Rect | Position box of the barcode in the original image |
cornerPoints | Point[] | Four corner coordinates of the barcode |
imageWidth | int | Original image width |
imageHeight | int | Original image height |
source | String | Decoding source (identifies which engine decoded it) |
5.4 Localization and Image Enhancement Wrappers
BarcodeYoloDetector
| Method | Return value | Description |
|---|---|---|
init(String modelPath) | boolean | Load the localization model and initialize |
isReady() | boolean | Whether 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() | void | Release the localization model |
BarcodeSrDetector
| Method | Return value | Description |
|---|---|---|
init(String modelPath) | boolean | Load the enhancement model and initialize |
isReady() | boolean | Whether 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() | void | Release the enhancement model |
5.5 Barcode Product Store BarcodeProductStore
| Method | Return value | Description |
|---|---|---|
BarcodeProductStore(Context) | Constructor | Open the local product store |
save(String barcode, String name, float price, String unit) | void | Create a record; unit is UNIT_PCS (by piece) or UNIT_KG (by weight) |
get(String barcode) | Item | Get a product record; returns null if it does not exist |
exists(String barcode) | boolean | Whether a record already exists |
remove(String barcode) | void | Delete a record |
getAll() | Map<String, Item> | All records |
normalize(String code) | String | Static 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
| File | Location (inside the AAR) | Description |
|---|---|---|
clip_vision_finetuned.rknn | assets/ | AI model for product image recognition |
barcode_det.rknn | assets/ | 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)
| File | Location (inside the AAR at jni/arm64-v8a/) | Description |
|---|---|---|
librknn4j.so | Java bridge library for model processing | |
librknnrt.so | Runtime support library for model processing | |
libbarcodeyolo.so | Native library for barcode localization | |
libbarcodesr.so | Native library for barcode image enhancement |
6.3 Local Storage Directories
| Path | Content |
|---|---|
filesDir/text_features.bin | Category recognition data (binary) |
filesDir/categories.json | Category and exclusion mapping |
外部文件目录/样本图片目录/images/<类别名>/ | Original local sample images |
外部文件目录/样本图片目录/thumbnails/<类别名>/ | Sample thumbnails |
7. Precautions and FAQ
- ABI restriction: The bundled native libraries only provide
arm64-v8a. Do not run recognition or scanning features on devices with other CPU architectures. - 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.
- Threading requirements: Do not perform time-consuming recognition or decoding calls on the main thread; process consecutive frames on a worker thread.
- 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. - 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. - 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. - 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.
- 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 class | Full package name | Purpose |
|---|---|---|
ActivationManager | com.aiweight.sdk.activation.ActivationManager | Activation code verification facade |
ActivationStatus | com.aiweight.sdk.activation.ActivationStatus | Activation result / status entity |
ActivationLoginActivity | com.aiweight.sdk.activation.ActivationLoginActivity | Bundled activation login page |
ClipHelper | com.aiweight.sdk.recognition.ClipHelper | AI recognition facade |
LocalImageManager | com.aiweight.sdk.recognition.LocalImageManager | Local sample image management |
InferenceResult | com.aiweight.sdk.recognition.InferenceResult | Recognition output container |
ClipInferenceWrapper | com.aiweight.sdk.recognition.clip.ClipInferenceWrapper | Model processing wrapper (internal) |
BarcodeScanActivity | com.aiweight.sdk.recognition.barcode.BarcodeScanActivity | Bundled barcode scan page |
BarcodeDecoder | com.aiweight.sdk.recognition.barcode.BarcodeDecoder | Multi-engine barcode decoder |
BarcodeYoloDetector | com.aiweight.sdk.recognition.barcode.BarcodeYoloDetector | Barcode / QR code localization wrapper |
BarcodeSrDetector | com.aiweight.sdk.recognition.barcode.BarcodeSrDetector | Barcode grayscale image enhancement wrapper |
BarcodeProductStore | com.aiweight.sdk.recognition.barcode.BarcodeProductStore | Local barcode product storage |
ScanOverlayView | com.aiweight.sdk.recognition.barcode.ScanOverlayView | Scan preview overlay view |
Appendix: Artifacts and Build
| Item | Description |
|---|---|
| Debug artifact | aiweight-sdk/build/outputs/aar/aiweight-sdk-debug.aar |
| Release build command | ./gradlew :aiweight-sdk:assembleRelease |
| Module source directory | aiweight-sdk/src/main/ |
| Module build script | aiweight-sdk/build.gradle |