CN | EN

Developer Center

Home-Developer Center-Documentation

AI Weighing Recognition Online Edition SDK (AAR) Integration Guide

Artifact: aiweight-online-sdk-debug.aar
Target project: Android online edition weighing checkout / weighing recognition applications
This document is for integration developers and describes how to import the AAR, its public entry points, the interfaces of each functional module, built-in files and notes.

Contents


1. Overview

1.1 Introduction

This AAR is a reusable SDK extracted as a whole from the online edition weighing recognition application. All business pages and flows are packaged inside, so integrators do not need to implement the checkout main flow again; they can use the following capabilities directly through the entry pages:

  1. Activation code / gateway verification: device ID generation, online activation code verification, local activation state persistence; built-in activation login page; when not activated, entering a feature page is automatically intercepted and redirected to the login page.
  2. Product management: product category creation, sample image capture and management, barcode product creation, category exclusion management.
  3. Photo capture and cutout: camera sample capture, manual box cropping / smart cutout, producing training sample images.
  4. AI product recognition checkout: real-time camera recognition, weighing linkage, shopping cart, discount pricing, receipt printing, customer display sync; the recognition AI model and category data are downloaded from the cloud to the device and then loaded.
  5. Barcode scanning: barcode / QR code locating, multi-engine decoding, local barcode product creation, built-in scan page.
  6. Weighing connection: serial scale connection, reading, weight stable detection.
  7. Customer display panel: serial customer display connection, text display, clear line and clear screen, cursor and indicator light control.
  8. Receipt settings and printing: receipt header / detail / QR code template configuration, USB receipt printer printing.
  9. Version restore: trace back historical backup versions (models, categories, sample images) from the server and restore them to the device.
  10. Online training upload: package sample images and upload them to the server for training, with training progress pushed back over WebSocket; each upload is also backed up to the server for later restore.

1.2 Differences Between Online and Standalone Editions

ItemOnline edition (this SDK)Description
Recognition AI model / category dataDownloaded from the cloud to the device private directory, then loadedThe AAR does not embed the recognition model; a network connection is required for the first download
Recognition / trainingNetwork dependentRecognition and training upload are unavailable offline; cutout can use smart cutout online
Version restoreBuilt inEvery upload is backed up to the server and can be restored by historical version
Barcode locating modelBundled with the AARassets/barcode_det.rknn
Activation verificationOnline verificationActivation code + device ID submitted to the gateway for verification

1.3 Applicable Environment

ItemRequirement
minSdkVersion25
compileSdkVersion / targetSdkVersion33
Supported ABIarm64-v8a (RK3566 / RK3576 class boards)
Build environmentAndroid Gradle Plugin 7.2.0 / Gradle 7.3.3 or above compatible versions
JDK bytecode level1.8
Third-party dependenciesappcompat, material, gson, okhttp, socket.io, online recognition runtime, barcode decoding library, etc. (coordinates in 2.2, already declared in the AAR)

1.4 Package Composition

CategoryContent
Main feature codeEntry menu, activation login, product management, recognition checkout, photo capture, cutout, scanning, training, version restore, network communication
Customer display / weighing / receipt codeCustomer display panel, serial scale management, weight stable detection, USB printing, receipt template and preview
Built-in AI modelsBarcode locating model (bundled with the AAR); recognition model and category data are downloaded from the cloud at runtime
Bundled native runtime librariesarm64-v8a runtime libraries packaged with the AAR
Local SDK jarCustomer display / scale serial SDK DisplaySDK-2.2.6.jar (carried in the AAR libs/)

2. Integration Steps

2.1 Import the AAR

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

2.2 Repositories and Third-party Dependencies

The SDK itself declares the following dependency coordinates in build.gradle. The AAR does not embed the classes and native so files of these third-party libraries; the integrating project must be able to access the corresponding repositories so that packaging pulls them in automatically:

repositories {
    google()
    mavenCentral()
}

dependencies {
    // SDK 已声明,集成方无需重复写;此处列出便于核对
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.viewpager2:viewpager2:1.0.0'

    // 联网:HTTP + WebSocket(Socket.IO)
    implementation 'com.squareup.okhttp3:okhttp:4.12.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
    implementation 'io.socket:socket.io-client:2.1.0'
    implementation 'com.google.code.gson:gson:2.10.1'

    // 在线识别(云端下载模型后本机推理)
    implementation 'com.microsoft.onnxruntime:onnxruntime-android:1.17.0'

    // 条码解码
    implementation 'com.google.mlkit:barcode-scanning:17.2.0'
    implementation 'com.google.zxing:core:3.5.2'
    implementation 'com.yanzhenjie.zbar:zbar:1.0.0'
}
Note: DisplaySDK-2.2.6.jar is already carried in the AAR libs/ directory, so integrators do not need to copy it separately; the native so files of third-party libraries such as onnxruntime and zbar are packaged into the APK automatically when the app resolves the maven dependencies above and are not inside the AAR jni/ directory, which is normal behavior.

2.3 Permission Declaration

The SDK AndroidManifest.xml already declares the following permissions, which are merged automatically with the integrating project Manifest; if the integrating project trims permissions, please confirm these are kept:

<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" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
Runtime permissions such as camera and storage are requested by each business page on entry; network permission must remain available for online features.

2.4 Initialization

The SDK does not require a mandatory initialization class registered in the Application. Each manager initializes itself on first use.

  • The entry MenuActivity is a complete menu page; after entering it checks the local activation code automatically; if no activation code is filled in, it redirects to the activation login page automatically.
  • If you need to release the recognition model cache when the app exits, call release() of ClipHelper in the exit flow (see 6.2).

2.5 Launch Entry

Launch the SDK main menu from any page of the integrating project:

Intent intent = new Intent(context, com.rockchip.gpadc.demo.MenuActivity.class);
// 建议加上新任务栈,避免与集成方原有栈混杂
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

3. Functional Modules and Entry Pages

The 12 registrable pages in the SDK are already registered in AndroidManifest.xml (fully qualified names), so integrators can construct an Intent and start them directly.

3.1 Page List

Page classFull package nameFunctionOrientation
MenuActivitycom.rockchip.gpadc.demo.MenuActivitySDK main menu (entry page)Portrait
GatewayLoginActivitycom.rockchip.gpadc.demo.GatewayLoginActivityActivation code / gateway login pagePortrait
ProductManageActivitycom.rockchip.gpadc.demo.ProductManageActivityProduct management (categories, samples, creation)Portrait
RealTimeActivitycom.rockchip.gpadc.demo.RealTimeActivityRecognition checkout page (recognition + weighing + cart + discount + receipt + customer display)Portrait
SmartCaptureActivitycom.rockchip.gpadc.demo.SmartCaptureActivitySmart photo capture of samplesPortrait
CropActivitycom.rockchip.gpadc.demo.CropActivityImage crop / cutoutPortrait
BarcodeScanActivitycom.rockchip.gpadc.demo.BarcodeScanActivityBarcode scan pageLandscape
LanguageActivitycom.rockchip.gpadc.demo.LanguageActivityLanguage switchingPortrait
SettingsActivitycom.rockchip.gpadc.demo.SettingsActivitySettings pagePortrait
ScalePanelActivitycom.example.displaydemo.ScalePanelActivityWeighing connection (serial scale configuration and reading)Portrait
PD108PanelActivitycom.example.displaydemo.PD108PanelActivityCustomer display panelPortrait
TicketSettingsActivitycom.example.displaydemo.TicketSettingsActivityReceipt template settingsLandscape

3.2 Inter-page Parameters (Intent Extra)

The following Extra values are mainly used for internal page navigation inside the SDK; if integrators start the corresponding page separately, they can pass them as described:

PageExtra keyTypeDescription
RealTimeActivityENABLE_LOCKbooleanWhether to enable device lock linkage; true when entered from the menu
BarcodeScanActivityEXTRA_RESULT (barcode_result)StringNormalized barcode returned on successful scan (returned via page setResult)
SmartCaptureActivitytarget_labelStringCategory name the current capture belongs to
SmartCaptureActivitylabel, image_countString / intCategory name and number of new images returned on capture completion
CropActivitycrop_image_pathStringPath of the image to crop
CropActivitycrop_labelStringCategory name the image belongs to
CropActivitycrop_has_boxbooleanWhether an initial box exists; false enters manual box drawing
CropActivitycrop_temp_path, image_type, has_manual_boxString / String / booleanTemporary image path, image type and whether manually boxed, returned on crop completion
Recommended usage: integrators enter from MenuActivity; page navigation and parameter passing inside the menu are handled by the SDK, so the Extra values above do not need to be assembled manually.

4. Activation Code / Gateway Verification Module

4.1 Verification Flow

  1. On first entering MenuActivity, the saved activation code is read from local SharedPreferences.
  2. No saved activation code: a prompt "请先输入激活码" is shown and the app redirects to the GatewayLoginActivity login page automatically.
  3. Activation code saved: before entering a feature page, device_id + activation_code + device_type are submitted to the gateway for online verification; if verification passes, access is granted for the current session; if it fails, the failure reason returned by the gateway is shown.
  4. After verification passes, the group number (group_id) returned by the gateway is written into the local cache as well.

4.2 Local Persistence

Storage name (SharedPreferences)KeyContent
device_configactivation_codeThe most recently entered / used activation code
device_configdevice_idDevice unique ID generated and saved on the device (android_ prefix + ANDROID_ID, random UUID when missing or default)
device_configgroup_idGroup number returned after gateway verification passes

4.3 Network Request Entry ApiClient

com.rockchip.gpadc.demo.network.ApiClient is a static HTTP facade:

MethodDescription
BASE_URL (static constant)Gateway HTTP address, see 5.1
postJson(String url, JsonObject json, ApiCallback cb)Submit a JSON object
postJson(String url, String jsonStr, ApiCallback cb)Submit a JSON string
get(String url, ApiCallback cb)GET request
ApiCallback.onSuccess(String response)Main thread callback, success response body
ApiCallback.onFailure(String error)Main thread callback, failure information (network error or HTTP status code)

Activation verification endpoint path: POST /api/device_verify_code, request body contains device_id, activation_code, device_type (label_client).

4.4 Built-in Login Page

Start GatewayLoginActivity directly:

Intent intent = new Intent(context, GatewayLoginActivity.class);
context.startActivity(intent);

The login page returns to the menu page after activation completes; the menu page re-verifies the activation state online when entering protected features later.


5. Network and Server Configuration

5.1 Server Addresses (hard-coded in source, verify on site before release)

PurposeConstant locationCurrent value
Gateway HTTP APIApiClient.BASE_URLhttp://192.168.0.91:5006
Gateway WebSocket (Socket.IO)WebSocketManager.SERVER_URLhttp://192.168.0.91:5006
Model / category data download gatewayModelDownloadManager.GATEWAY_URLhttp://192.168.0.91:5006
Cloud file download domainConcatenated prefix inside RestoreManagerhttp://aiorderingfooden.2020oa.com/
The addresses above are hard-coded LAN / cloud addresses in the source. When deploying on site, change the corresponding constants according to the actual gateway IP, port and cloud domain; HTTP cleartext traffic is already allowed in the SDK Manifest via usesCleartextTraffic="true".

5.2 WebSocket Communication WebSocketManager

com.rockchip.gpadc.demo.network.WebSocketManager wraps the Socket.IO long connection and is used for training progress push, task updates, device lock / kick-out and other events:

Method / memberDescription
WebSocketManager(WsEventListener listener)Connects on construction, 15 second heartbeat, automatic reconnect (up to 10 times)
connect() / disconnect()Manual connect / disconnect
bindDevice(String deviceId)Report the device ID after connecting to complete authentication
reportProgress(String deviceId, String taskId, int progress, String log)Report training progress
isConnected()Whether currently connected and authenticated
sendPing()Manually send a heartbeat check

WsEventListener callbacks: onConnect(), onDisconnect(), onError(String error), onAuthSuccess(), onAuthFailed(String msg), onTaskUpdate(JSONObject data), onTrainProgress(JSONObject data).


6. AI Recognition and Product Management Module

6.1 Module Composition

ClassPackage nameDescription
ClipHelpercom.rockchip.gpadc.demoRecognition facade, singleton entry
ClipInferenceWrappercom.rockchip.gpadc.demo.clipAI model processing wrapper (internal use, generally not called directly)
LocalImageManagercom.rockchip.gpadc.demoLocal sample image saving, scanning, deletion, thumbnails
ProductManageActivitycom.rockchip.gpadc.demoProduct management page (category creation, sample management, exclusions)
DetectionResult / InferenceResultcom.rockchip.gpadc.demoRecognition result entities (internal use)

6.2 Recognition Facade ClipHelper

Get the singleton:

ClipHelper helper = ClipHelper.getInstance(context);
MethodReturn valueDescription
getInstance(Context)ClipHelperGet the singleton (static, thread safe)
resetInstance()voidReset the singleton (static)
isReady()booleanWhether the AI model and category data are ready
initVisionModel()booleanLoad the recognition AI model
reloadModels()booleanReload the models
clipClassifyTopN(Bitmap, int topN)List<TopResult>Return the top N candidate categories with the highest similarity
clipClassify(Bitmap)ResultReturn a single stabilized recognition result
clipClassify(Bitmap, RectF location)ResultRecognize within the specified region
clipClassify(Bitmap, RectF location, int trackId)ResultRecognize within the specified region with tracking ID, with consecutive frame stabilization
extractImageFeature(Bitmap)float[]Extract recognition reference data of a single image (for internal comparison)
getCategoryCount()intCurrent number of positive sample categories
getAllCategories() / getCategoryMap()Map<String, Boolean>All categories and their exclusion status
getPositiveCategories()Map<String, Boolean>Positive sample categories
getExcludeList()List<String>List of excluded categories
isExclude(String label)booleanWhether the specified category is excluded
toggleExcludeStatus(String label)booleanToggle the excluded / normal status of a category
removeCategory(String label)booleanDelete the specified category and its data
addTextCategory(String label, boolean isExclude, float[] feature)booleanAdd category recognition data to the in-memory cache
getFeature(String label)float[]Get the reference data of the specified category
loadFeaturesFromUrls(String binUrl, String jsonUrl, LoadCallback)voidDownload category data from cloud URLs and load it (online edition)
loadCategoriesFromFiles()booleanLoad category data from local files
refreshCategoriesFromFiles() / reloadFeatures()voidRefresh the category data in memory
forceReloadFeatures()booleanForce reload of category data
saveFeaturesToFile()booleanWrite the current category data to a local file
getThreshold() / setThreshold(float)float / voidRead / write the similarity threshold
clearStableCache(int trackId) / clearAllStableCache()voidClear the consecutive frame stabilization cache
release()voidRelease model and cache resources, call when the app exits

Result entities

  • ClipHelper.TopResult: clsName (category name), score (similarity 0~1).
  • ClipHelper.Result: recognition output container, field meanings correspond to TopResult.

6.3 Local Sample Image Management LocalImageManager

MethodReturn valueDescription
LocalImageManager(Context)ConstructorInitialize the local sample directory
saveImage(Bitmap, String label)StringSave a sample image to the specified category directory, 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 per category
deleteImage(String filePath)booleanDelete the specified sample image
getThumbnail(String filePath)BitmapRead the sample thumbnail
getImage(String filePath)BitmapRead the original sample image

6.4 Usage Example

Recognition 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    相似度
}

Release resources:

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

7. Photo Capture and Cutout Module

7.1 Pages and Views

ClassPackage nameDescription
SmartCaptureActivitycom.rockchip.gpadc.demoCamera sample capture page, continuous shooting by category and jump to cutout
CropActivitycom.rockchip.gpadc.demoCrop / cutout page, supports manual box drawing and smart cutout
CropDrawViewcom.rockchip.gpadc.demo.viewCrop box drawing view
RoiOverlayViewcom.example.displaydemoROI box selection overlay view

7.2 Launch Photo Capture

Intent intent = new Intent(context, SmartCaptureActivity.class);
intent.putExtra("target_label", "绿色草莓"); // 归属类别
context.startActivity(intent);

After capture completes, the page returns label (category) and image_count (number of new images this time).

7.3 Launch Cutout

Intent intent = new Intent(context, CropActivity.class);
intent.putExtra(CropActivity.EXTRA_IMAGE_PATH, imagePath);
intent.putExtra(CropActivity.EXTRA_LABEL, label);
intent.putExtra("crop_has_box", false); // 无自动框,进入手动拉框
context.startActivity(intent);

After cropping completes, crop_temp_path (temporary image path), image_type (image type) and has_manual_box (whether manually boxed) are returned.


8. Barcode Scanning Module

8.1 Module Composition

ClassPackage nameDescription
BarcodeScanActivitycom.rockchip.gpadc.demoBuilt-in scan page (preview + locating + decoding + result return)
BarcodeDecodercom.rockchip.gpadc.demoMulti-engine decoder (Bitmap / NV21 / grayscale frame)
BarcodeYoloDetectorcom.rockchip.gpadc.demoBarcode / QR code locating wrapper
BarcodeSrDetectorcom.rockchip.gpadc.demoBarcode grayscale image enhancement wrapper
BarcodeProductStorecom.rockchip.gpadc.demoLocal storage for created barcode products
ScanOverlayViewcom.rockchip.gpadc.demoScan preview overlay view

8.2 Launch the Built-in Scan Page

Launch 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 为归一化后的条码
                        }
                    }
                });

mScanLauncher.launch(new Intent(this, BarcodeScanActivity.class));
  • After successful recognition the page returns Activity.RESULT_OK and returns the barcode via EXTRA_RESULT; cancel or direct back returns nothing.
  • The scan page has a built-in activation gate: scanning is not entered until activation verification passes.

8.3 Barcode Product Store BarcodeProductStore

MethodReturn valueDescription
BarcodeProductStore(Context)ConstructorOpen the local product storage
save(String barcode, String name, float price, String unit)voidCreate a product; unit is UNIT_PCS (by piece) or UNIT_KG (by weight)
get(String barcode)ItemGet the created product; returns null if not found
exists(String barcode)booleanWhether the product has been created
remove(String barcode)voidDelete the created product
getAll()Map<String, Item>All created products
normalize(String code)StringStatic method; strips non-alphanumeric characters and pads leading zeros when too short

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

8.4 Locator and Image Enhancement Wrappers

BarcodeYoloDetector: init(String modelPath), isReady(), detect(byte[] nv21, int w, int h) (returns an array of detection boxes), deinit().

BarcodeSrDetector: init(String modelPath), isReady(), upscale(byte[] gray, int inW, int inH) (grayscale 2x enhancement), deinit().


9. Weighing / Customer Display / Receipt Printing Module

9.1 Weighing Management ScaleManager

com.example.displaydemo.ScaleManager:

MethodReturn valueDescription
ScaleManager(ScaleListener listener)ConstructorRegister the reading callback
connect(String devicePath, int baudRate)voidOpen the serial scale connection
isConnected()booleanWhether the serial port is connected
disconnect()voidDisconnect the serial scale

ScaleListener callbacks: onWeight(float weightKg, int status) (weight in kg and status), onFrame(String hex, String detail) (raw frame), onStatusChanged(String status).

Weight stable detection is handled by WeightStableDetector: onWeight(float weightKg, int status), reset().

The weighing connection configuration page is ScalePanelActivity.

9.2 Customer Display Panel PD108PanelActivity

com.example.displaydemo.PD108PanelActivity is the built-in customer display debug / panel page, providing serial port selection, baud rate, text display, clear line and clear screen, cursor state, hold test, indicator light control and other operations; the underlying serial customer display is driven by DisplaySDK-2.2.6.jar.

9.3 Receipt Printing UsbPrinterManager

com.example.displaydemo.UsbPrinterManager:

MethodReturn valueDescription
UsbPrinterManager(Context ctx)ConstructorInitialize the USB printer management
connect(OnConnectListener listener)voidRequest USB permission and connect the printer
isConnected()booleanWhether the printer is connected
sendRaw(byte[] data)booleanSend raw print bytes
printQrCode(String content)voidPrint a QR code
printCartReceipt(String orderNo, String cashier, ...)voidPrint the cart receipt (based on cart details and pricing result)
disconnect()voidDisconnect the printer

9.4 Receipt Template TicketConfig / TicketPreviewView

ClassDescription
TicketConfigReceipt template configuration (header, details, separator lines, etc.), persisted via save(Context), separator obtained via lineSeparator()
TicketPreviewViewReceipt preview view, applies the template via setConfig(TicketConfig cfg)
TicketSettingsActivityReceipt template settings page (landscape), live preview

9.5 Cart Item CartItem

com.example.displaydemo.CartItem is a cart line item: supports incCount() / decCount() to increase or decrease quantity, and isByPcs() to determine the pricing unit.


10. Version Restore and Online Training Upload

10.1 Version Restore RestoreManager

com.rockchip.gpadc.demo.RestoreManager: traces back historical backup versions (recognition model, category data, sample images) from the server and restores them to the device; every training upload keeps a backup on the server for later restore.

MethodReturn valueDescription
RestoreManager(Activity activity)ConstructorInitialize the restore manager
setListener(OnRestoreListener listener)voidRegister restore progress / result callbacks
showRestoreVersionDialog()voidShow the historical version selection and perform the restore
release()voidRelease resources

OnRestoreListener callbacks: onRestoreStart(String taskName, String taskId), onRestoreProgress(int progress, String message), onRestoreComplete(String taskName, int modelCount, int categoryCount, int imageCount), onRestoreFailed(String error).

After restoration completes, a local broadcast (action CLIP_FEATURES_UPDATED, Extra task_name) notifies listeners to refresh the recognition data.

10.2 Online Training Upload TrainManager

com.rockchip.gpadc.demo.TrainManager: packages sample images and uploads them to the server for training, receives training progress over WebSocket, and downloads the updated model / category data to the device when training completes.

MethodReturn valueDescription
TrainManager(AppCompatActivity activity, ClipHelper clipHelper, String deviceId, TrainCallback callback)ConstructorInitialize, automatically check the cached training task and connect WebSocket
submitTrainTask(List<PhotoItem> photos, String taskName, String taskType, String oldModel, boolean reuseOldDataset, String epochs, String lr, String augNum, String augMaxObj)voidSubmit a training task
release()voidRelease WebSocket and cache resources

TrainCallback callbacks: onTrainingSubmitted(String taskId), onTrainingComplete(String taskId), onTrainingFailed(String error), onRefreshUI(), onRefreshList(), onRefreshPhotoPreview(), onUpdateTrainButtonState(boolean inProgress, boolean hasNew), onProgressUpdate(int progress, String log).

10.3 Model Download ModelDownloadManager

com.rockchip.gpadc.demo.ModelDownloadManager: the download entry for the online edition recognition model and category data.

MethodReturn valueDescription
ModelDownloadManager(Activity activity)ConstructorInitialize the download manager
showModelSelectDialog()voidShow the model selection dialog
showModelDownloadDialog()voidShow the model download dialog
showClipDownloadDialog()voidShow the category data download dialog
downloadModel(String modelName)voidDownload the specified recognition model
downloadClip(ClipFileItem item)voidDownload the specified category data item
downloadLatestClipAssets()voidDownload the latest category data assets
release()voidRelease resources
The trial build includes 4 categories available for download; the model / category data download must be completed online before the first recognition.

11. Built-in File List

11.1 Built-in AI Models (AAR assets/)

FileLocation (inside the AAR)Description
barcode_det.rknnassets/Barcode / QR code locating AI model
The recognition AI model and category data are not bundled in the AAR; at runtime they are downloaded from the gateway / cloud to the device private directory and then loaded; no recognition data is available offline.

11.2 Bundled Native Libraries (AAR jni/arm64-v8a/)

FileDescription
librknn4j.soModel processing Java bridge library
librknnrt.soModel processing runtime support library
libbarcodeyolo.soBarcode locating companion native library (built with CMake)
libbarcodesr.soBarcode image enhancement companion native library (built with CMake)
libopencv_java3.soImage processing library
librga.soGraphics acceleration library
libserial_port_wm.soSerial communication library

11.3 Local SDK Jar (AAR libs/)

FileDescription
DisplaySDK-2.2.6.jarCustomer display / scale serial SDK, carried with the AAR

11.4 Native Libraries Brought in by Third-party Dependencies

The native so files of third-party libraries such as onnxruntime, zbar / barhopper / iconv are not inside the AAR jni/ directory; they are packaged into the APK automatically when the integrating app resolves the maven dependencies listed in 2.2; this is the normal packaging behavior of the AAR and no manual copy is needed.

11.5 Local Storage Directories (generated at runtime)

PathContent
Category data binary and json under filesDir/Local recognition category data cache
App external files directory / sample image directoryOriginal sample images and thumbnails
App private cache directoryDownloaded recognition model, category data, training temporary files

12. Notes and FAQ

  1. ABI restriction: the bundled native libraries only provide arm64-v8a; do not run recognition, scanning, weighing / customer display serial features on devices with other CPU architectures.
  2. Network dependency: recognition, model / category data download, training upload, version restore and activation verification all depend on the network; these features are unavailable offline. Cutout can use smart cutout online.
  3. First download takes time: the model and category data must be downloaded online before entering the recognition feature for the first time; empty recognition results during the download are normal; reserve download time in the checkout startup flow.
  4. Verify gateway addresses: the gateway IP / port and cloud domain in the source are on-site test values; check and modify each item of the 5.1 list before going live.
  5. Thread requirements: do not call time-consuming operations such as recognition, decoding and downloading on the main thread; process consecutive frames on a worker thread.
  6. Resource release: when the app exits or the recognition feature is no longer used, call ClipHelper.release(), TrainManager.release(), ModelDownloadManager.release(), RestoreManager.release() to release the model and WebSocket caches; each page already releases the corresponding resources in onDestroy.
  7. Activation gate: before entering protected features such as product management, recognition checkout and version restore in the menu, the activation code is re-verified online automatically; when not activated or verification fails, the reason is shown and the app returns to the login page.
  8. Cleartext HTTP: the SDK has allowed cleartext traffic (usesCleartextTraffic="true"); if the on-site gateway / cloud switches to HTTPS, adjust the 5.1 addresses and the network security configuration accordingly.
  9. Serial devices: the scale and customer display are connected via serial ports; select the correct serial port and baud rate on the weighing connection / customer display panel page; serial device nodes and permissions depend on the on-site device environment.
  10. Keep package names unchanged: the SDK keeps its original dual-package structure (com.rockchip.gpadc.demo.* and com.example.displaydemo.*); integrator code must not change the package or rename these classes, to avoid breaking resource R classes and references.

13. Class and Package Name Reference

13.1 Main Feature Package com.rockchip.gpadc.demo

Public classPurpose
MenuActivitySDK main menu entry page
GatewayLoginActivityActivation code / gateway login page
ProductManageActivityProduct management page
RealTimeActivityRecognition checkout page
SmartCaptureActivityPhoto capture page
CropActivityCrop / cutout page
BarcodeScanActivityBarcode scan page
LanguageActivityLanguage switching page
SettingsActivitySettings page
ClipHelperAI recognition facade
ClipInferenceWrapperAI model processing wrapper (internal)
LocalImageManagerLocal sample image management
TrainManagerOnline training upload manager
ModelDownloadManagerModel / category data download manager
RestoreManagerVersion restore manager
BarcodeDecoderMulti-engine barcode decoder
BarcodeYoloDetectorBarcode / QR code locating wrapper
BarcodeSrDetectorBarcode grayscale image enhancement wrapper
BarcodeProductStoreLocal barcode product storage
ScanOverlayViewScan preview overlay view
DetectionResult / InferenceResultRecognition result entities
ImageBufferQueueImage frame buffer queue (internal)
LocaleHelperMulti-language utility
BaseActivityMain feature base class
network.ApiClientGateway HTTP facade
network.WebSocketManagerGateway WebSocket long connection
rga.RGA / rga.HALDefineGraphics acceleration wrapper (internal)
view.CropDrawViewCrop box drawing view

13.2 Customer Display / Weighing / Receipt Package com.example.displaydemo

Public classPurpose
ScalePanelActivityWeighing connection configuration page
ScaleManagerSerial scale reading management
WeightStableDetectorWeight stable detection
PD108PanelActivityCustomer display panel page
UsbPrinterManagerUSB receipt printer management
TicketSettingsActivityReceipt template settings page
TicketConfigReceipt template configuration entity
TicketPreviewViewReceipt preview view
CartItemCart line item entity
RoiOverlayViewROI box selection overlay view
ToastUtilsToast utility
InitApplicationApp-level context holder (optional registration, generally not called directly)
BaseActivityCustomer display / weighing module base class

Appendix: Artifacts and Build

ItemDescription
Debug artifactaiweight-online-sdk/build/outputs/aar/aiweight-online-sdk-debug.aar
Module source directoryaiweight-online-sdk/src/main/
Module build scriptaiweight-online-sdk/build.gradle
Debug build command./gradlew :aiweight-online-sdk:assembleDebug
Release build command./gradlew :aiweight-online-sdk:assembleRelease
SDK namespacecom.example.displaydemo (same as the resource R class package name)