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
- 2. Integration Steps
- 3. Functional Modules and Entry Pages
- 4. Activation Code / Gateway Verification Module
- 5. Network and Server Configuration
- 6. AI Recognition and Product Management Module
- 7. Photo Capture and Cutout Module
- 8. Barcode Scanning Module
- 9. Weighing / Customer Display / Receipt Printing Module
- 10. Version Restore and Online Training Upload
- 11. Built-in File List
- 12. Notes and FAQ
- 13. Class and Package Name Reference
- Appendix: Artifacts and Build
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:
- 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.
- Product management: product category creation, sample image capture and management, barcode product creation, category exclusion management.
- Photo capture and cutout: camera sample capture, manual box cropping / smart cutout, producing training sample images.
- 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.
- Barcode scanning: barcode / QR code locating, multi-engine decoding, local barcode product creation, built-in scan page.
- Weighing connection: serial scale connection, reading, weight stable detection.
- Customer display panel: serial customer display connection, text display, clear line and clear screen, cursor and indicator light control.
- Receipt settings and printing: receipt header / detail / QR code template configuration, USB receipt printer printing.
- Version restore: trace back historical backup versions (models, categories, sample images) from the server and restore them to the device.
- 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
| Item | Online edition (this SDK) | Description |
|---|---|---|
| Recognition AI model / category data | Downloaded from the cloud to the device private directory, then loaded | The AAR does not embed the recognition model; a network connection is required for the first download |
| Recognition / training | Network dependent | Recognition and training upload are unavailable offline; cutout can use smart cutout online |
| Version restore | Built in | Every upload is backed up to the server and can be restored by historical version |
| Barcode locating model | Bundled with the AAR | assets/barcode_det.rknn |
| Activation verification | Online verification | Activation code + device ID submitted to the gateway for verification |
1.3 Applicable Environment
| Item | Requirement |
|---|---|
| minSdkVersion | 25 |
| compileSdkVersion / targetSdkVersion | 33 |
| Supported ABI | arm64-v8a (RK3566 / RK3576 class boards) |
| Build environment | Android Gradle Plugin 7.2.0 / Gradle 7.3.3 or above compatible versions |
| JDK bytecode level | 1.8 |
| Third-party dependencies | appcompat, 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
| Category | Content |
|---|---|
| Main feature code | Entry menu, activation login, product management, recognition checkout, photo capture, cutout, scanning, training, version restore, network communication |
| Customer display / weighing / receipt code | Customer display panel, serial scale management, weight stable detection, USB printing, receipt template and preview |
| Built-in AI models | Barcode locating model (bundled with the AAR); recognition model and category data are downloaded from the cloud at runtime |
| Bundled native runtime libraries | arm64-v8a runtime libraries packaged with the AAR |
| Local SDK jar | Customer display / scale serial SDK DisplaySDK-2.2.6.jar (carried in the AAR libs/) |
2. Integration Steps
2.1 Import the AAR
- Copy
aiweight-online-sdk-debug.aarinto theapp/libs/directory of the integrating project (create the directory if it does not exist). - Add the following to
dependenciesin the integrating projectapp/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.jaris already carried in the AARlibs/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 AARjni/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
MenuActivityis 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()ofClipHelperin 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 class | Full package name | Function | Orientation |
|---|---|---|---|
MenuActivity | com.rockchip.gpadc.demo.MenuActivity | SDK main menu (entry page) | Portrait |
GatewayLoginActivity | com.rockchip.gpadc.demo.GatewayLoginActivity | Activation code / gateway login page | Portrait |
ProductManageActivity | com.rockchip.gpadc.demo.ProductManageActivity | Product management (categories, samples, creation) | Portrait |
RealTimeActivity | com.rockchip.gpadc.demo.RealTimeActivity | Recognition checkout page (recognition + weighing + cart + discount + receipt + customer display) | Portrait |
SmartCaptureActivity | com.rockchip.gpadc.demo.SmartCaptureActivity | Smart photo capture of samples | Portrait |
CropActivity | com.rockchip.gpadc.demo.CropActivity | Image crop / cutout | Portrait |
BarcodeScanActivity | com.rockchip.gpadc.demo.BarcodeScanActivity | Barcode scan page | Landscape |
LanguageActivity | com.rockchip.gpadc.demo.LanguageActivity | Language switching | Portrait |
SettingsActivity | com.rockchip.gpadc.demo.SettingsActivity | Settings page | Portrait |
ScalePanelActivity | com.example.displaydemo.ScalePanelActivity | Weighing connection (serial scale configuration and reading) | Portrait |
PD108PanelActivity | com.example.displaydemo.PD108PanelActivity | Customer display panel | Portrait |
TicketSettingsActivity | com.example.displaydemo.TicketSettingsActivity | Receipt template settings | Landscape |
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:
| Page | Extra key | Type | Description |
|---|---|---|---|
RealTimeActivity | ENABLE_LOCK | boolean | Whether to enable device lock linkage; true when entered from the menu |
BarcodeScanActivity | EXTRA_RESULT (barcode_result) | String | Normalized barcode returned on successful scan (returned via page setResult) |
SmartCaptureActivity | target_label | String | Category name the current capture belongs to |
SmartCaptureActivity | label, image_count | String / int | Category name and number of new images returned on capture completion |
CropActivity | crop_image_path | String | Path of the image to crop |
CropActivity | crop_label | String | Category name the image belongs to |
CropActivity | crop_has_box | boolean | Whether an initial box exists; false enters manual box drawing |
CropActivity | crop_temp_path, image_type, has_manual_box | String / String / boolean | Temporary 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
- On first entering
MenuActivity, the saved activation code is read from localSharedPreferences. - No saved activation code: a prompt "请先输入激活码" is shown and the app redirects to the
GatewayLoginActivitylogin page automatically. - Activation code saved: before entering a feature page,
device_id+activation_code+device_typeare 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. - 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) | Key | Content |
|---|---|---|
device_config | activation_code | The most recently entered / used activation code |
device_config | device_id | Device unique ID generated and saved on the device (android_ prefix + ANDROID_ID, random UUID when missing or default) |
device_config | group_id | Group number returned after gateway verification passes |
4.3 Network Request Entry ApiClient
com.rockchip.gpadc.demo.network.ApiClient is a static HTTP facade:
| Method | Description |
|---|---|
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)
| Purpose | Constant location | Current value |
|---|---|---|
| Gateway HTTP API | ApiClient.BASE_URL | http://192.168.0.91:5006 |
| Gateway WebSocket (Socket.IO) | WebSocketManager.SERVER_URL | http://192.168.0.91:5006 |
| Model / category data download gateway | ModelDownloadManager.GATEWAY_URL | http://192.168.0.91:5006 |
| Cloud file download domain | Concatenated prefix inside RestoreManager | http://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 / member | Description |
|---|---|
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
| Class | Package name | Description |
|---|---|---|
ClipHelper | com.rockchip.gpadc.demo | Recognition facade, singleton entry |
ClipInferenceWrapper | com.rockchip.gpadc.demo.clip | AI model processing wrapper (internal use, generally not called directly) |
LocalImageManager | com.rockchip.gpadc.demo | Local sample image saving, scanning, deletion, thumbnails |
ProductManageActivity | com.rockchip.gpadc.demo | Product management page (category creation, sample management, exclusions) |
DetectionResult / InferenceResult | com.rockchip.gpadc.demo | Recognition result entities (internal use) |
6.2 Recognition Facade ClipHelper
Get the singleton:
ClipHelper helper = ClipHelper.getInstance(context);| Method | Return value | Description |
|---|---|---|
getInstance(Context) | ClipHelper | Get the singleton (static, thread safe) |
resetInstance() | void | Reset the singleton (static) |
isReady() | boolean | Whether the AI model and category data are ready |
initVisionModel() | boolean | Load the recognition AI model |
reloadModels() | boolean | Reload the models |
clipClassifyTopN(Bitmap, int topN) | List<TopResult> | Return the top N candidate categories with the highest similarity |
clipClassify(Bitmap) | Result | Return a single stabilized recognition result |
clipClassify(Bitmap, RectF location) | Result | Recognize within the specified region |
clipClassify(Bitmap, RectF location, int trackId) | Result | Recognize 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() | int | Current 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) | boolean | Whether the specified category is excluded |
toggleExcludeStatus(String label) | boolean | Toggle the excluded / normal status of a category |
removeCategory(String label) | boolean | Delete the specified category and its data |
addTextCategory(String label, boolean isExclude, float[] feature) | boolean | Add 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) | void | Download category data from cloud URLs and load it (online edition) |
loadCategoriesFromFiles() | boolean | Load category data from local files |
refreshCategoriesFromFiles() / reloadFeatures() | void | Refresh the category data in memory |
forceReloadFeatures() | boolean | Force reload of category data |
saveFeaturesToFile() | boolean | Write the current category data to a local file |
getThreshold() / setThreshold(float) | float / void | Read / write the similarity threshold |
clearStableCache(int trackId) / clearAllStableCache() | void | Clear the consecutive frame stabilization cache |
release() | void | Release 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
| Method | Return value | Description |
|---|---|---|
LocalImageManager(Context) | Constructor | Initialize the local sample directory |
saveImage(Bitmap, String label) | String | Save 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) | boolean | Delete the specified sample image |
getThumbnail(String filePath) | Bitmap | Read the sample thumbnail |
getImage(String filePath) | Bitmap | Read 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
| Class | Package name | Description |
|---|---|---|
SmartCaptureActivity | com.rockchip.gpadc.demo | Camera sample capture page, continuous shooting by category and jump to cutout |
CropActivity | com.rockchip.gpadc.demo | Crop / cutout page, supports manual box drawing and smart cutout |
CropDrawView | com.rockchip.gpadc.demo.view | Crop box drawing view |
RoiOverlayView | com.example.displaydemo | ROI 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
| Class | Package name | Description |
|---|---|---|
BarcodeScanActivity | com.rockchip.gpadc.demo | Built-in scan page (preview + locating + decoding + result return) |
BarcodeDecoder | com.rockchip.gpadc.demo | Multi-engine decoder (Bitmap / NV21 / grayscale frame) |
BarcodeYoloDetector | com.rockchip.gpadc.demo | Barcode / QR code locating wrapper |
BarcodeSrDetector | com.rockchip.gpadc.demo | Barcode grayscale image enhancement wrapper |
BarcodeProductStore | com.rockchip.gpadc.demo | Local storage for created barcode products |
ScanOverlayView | com.rockchip.gpadc.demo | Scan 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_OKand returns the barcode viaEXTRA_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
| Method | Return value | Description |
|---|---|---|
BarcodeProductStore(Context) | Constructor | Open the local product storage |
save(String barcode, String name, float price, String unit) | void | Create a product; unit is UNIT_PCS (by piece) or UNIT_KG (by weight) |
get(String barcode) | Item | Get the created product; returns null if not found |
exists(String barcode) | boolean | Whether the product has been created |
remove(String barcode) | void | Delete the created product |
getAll() | Map<String, Item> | All created products |
normalize(String code) | String | Static 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:
| Method | Return value | Description |
|---|---|---|
ScaleManager(ScaleListener listener) | Constructor | Register the reading callback |
connect(String devicePath, int baudRate) | void | Open the serial scale connection |
isConnected() | boolean | Whether the serial port is connected |
disconnect() | void | Disconnect 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:
| Method | Return value | Description |
|---|---|---|
UsbPrinterManager(Context ctx) | Constructor | Initialize the USB printer management |
connect(OnConnectListener listener) | void | Request USB permission and connect the printer |
isConnected() | boolean | Whether the printer is connected |
sendRaw(byte[] data) | boolean | Send raw print bytes |
printQrCode(String content) | void | Print a QR code |
printCartReceipt(String orderNo, String cashier, ...) | void | Print the cart receipt (based on cart details and pricing result) |
disconnect() | void | Disconnect the printer |
9.4 Receipt Template TicketConfig / TicketPreviewView
| Class | Description |
|---|---|
TicketConfig | Receipt template configuration (header, details, separator lines, etc.), persisted via save(Context), separator obtained via lineSeparator() |
TicketPreviewView | Receipt preview view, applies the template via setConfig(TicketConfig cfg) |
TicketSettingsActivity | Receipt 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.
| Method | Return value | Description |
|---|---|---|
RestoreManager(Activity activity) | Constructor | Initialize the restore manager |
setListener(OnRestoreListener listener) | void | Register restore progress / result callbacks |
showRestoreVersionDialog() | void | Show the historical version selection and perform the restore |
release() | void | Release 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.
| Method | Return value | Description |
|---|---|---|
TrainManager(AppCompatActivity activity, ClipHelper clipHelper, String deviceId, TrainCallback callback) | Constructor | Initialize, 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) | void | Submit a training task |
release() | void | Release 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.
| Method | Return value | Description |
|---|---|---|
ModelDownloadManager(Activity activity) | Constructor | Initialize the download manager |
showModelSelectDialog() | void | Show the model selection dialog |
showModelDownloadDialog() | void | Show the model download dialog |
showClipDownloadDialog() | void | Show the category data download dialog |
downloadModel(String modelName) | void | Download the specified recognition model |
downloadClip(ClipFileItem item) | void | Download the specified category data item |
downloadLatestClipAssets() | void | Download the latest category data assets |
release() | void | Release 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/)
| File | Location (inside the AAR) | Description |
|---|---|---|
barcode_det.rknn | assets/ | 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/)
| File | Description |
|---|---|
librknn4j.so | Model processing Java bridge library |
librknnrt.so | Model processing runtime support library |
libbarcodeyolo.so | Barcode locating companion native library (built with CMake) |
libbarcodesr.so | Barcode image enhancement companion native library (built with CMake) |
libopencv_java3.so | Image processing library |
librga.so | Graphics acceleration library |
libserial_port_wm.so | Serial communication library |
11.3 Local SDK Jar (AAR libs/)
| File | Description |
|---|---|
DisplaySDK-2.2.6.jar | Customer 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)
| Path | Content |
|---|---|
Category data binary and json under filesDir/ | Local recognition category data cache |
| App external files directory / sample image directory | Original sample images and thumbnails |
| App private cache directory | Downloaded recognition model, category data, training temporary files |
12. Notes and FAQ
- 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. - 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.
- 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.
- 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.
- 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.
- 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 inonDestroy. - 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.
- 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. - 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.
- Keep package names unchanged: the SDK keeps its original dual-package structure (
com.rockchip.gpadc.demo.*andcom.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 class | Purpose |
|---|---|
MenuActivity | SDK main menu entry page |
GatewayLoginActivity | Activation code / gateway login page |
ProductManageActivity | Product management page |
RealTimeActivity | Recognition checkout page |
SmartCaptureActivity | Photo capture page |
CropActivity | Crop / cutout page |
BarcodeScanActivity | Barcode scan page |
LanguageActivity | Language switching page |
SettingsActivity | Settings page |
ClipHelper | AI recognition facade |
ClipInferenceWrapper | AI model processing wrapper (internal) |
LocalImageManager | Local sample image management |
TrainManager | Online training upload manager |
ModelDownloadManager | Model / category data download manager |
RestoreManager | Version restore manager |
BarcodeDecoder | Multi-engine barcode decoder |
BarcodeYoloDetector | Barcode / QR code locating wrapper |
BarcodeSrDetector | Barcode grayscale image enhancement wrapper |
BarcodeProductStore | Local barcode product storage |
ScanOverlayView | Scan preview overlay view |
DetectionResult / InferenceResult | Recognition result entities |
ImageBufferQueue | Image frame buffer queue (internal) |
LocaleHelper | Multi-language utility |
BaseActivity | Main feature base class |
network.ApiClient | Gateway HTTP facade |
network.WebSocketManager | Gateway WebSocket long connection |
rga.RGA / rga.HALDefine | Graphics acceleration wrapper (internal) |
view.CropDrawView | Crop box drawing view |
13.2 Customer Display / Weighing / Receipt Package com.example.displaydemo
| Public class | Purpose |
|---|---|
ScalePanelActivity | Weighing connection configuration page |
ScaleManager | Serial scale reading management |
WeightStableDetector | Weight stable detection |
PD108PanelActivity | Customer display panel page |
UsbPrinterManager | USB receipt printer management |
TicketSettingsActivity | Receipt template settings page |
TicketConfig | Receipt template configuration entity |
TicketPreviewView | Receipt preview view |
CartItem | Cart line item entity |
RoiOverlayView | ROI box selection overlay view |
ToastUtils | Toast utility |
InitApplication | App-level context holder (optional registration, generally not called directly) |
BaseActivity | Customer display / weighing module base class |
Appendix: Artifacts and Build
| Item | Description |
|---|---|
| Debug artifact | aiweight-online-sdk/build/outputs/aar/aiweight-online-sdk-debug.aar |
| Module source directory | aiweight-online-sdk/src/main/ |
| Module build script | aiweight-online-sdk/build.gradle |
| Debug build command | ./gradlew :aiweight-online-sdk:assembleDebug |
| Release build command | ./gradlew :aiweight-online-sdk:assembleRelease |
| SDK namespace | com.example.displaydemo (same as the resource R class package name) |