CN | EN

Developer Center

Home-Developer Center-Documentation

AI Morning Check Recognition SDK (AAR) Integration Guide

Artifact: hands-sdk-debug.aar
Target projects: Android hand morning check / accessory detection applications (real-time recognition, image recognition, sample capture, category management, model updates)
This document is intended for integrators' developers and describes how to import the AAR, the public entry points, engine and data APIs, built-in models and native libraries, the activation code mechanism, and notes.

Contents


1. Overview

1.1 Introduction

This AAR is a reusable SDK extracted from the whole morning check recognition standalone application. All business pages and recognition pipelines are packaged inside, and integrators can use them directly through the entry pages:

  1. Real-time recognition: the camera finds the hand in real time, distinguishes palm / back of hand, and determines the accessory category after a stable frame is captured; single-hand / two-hand supported.
  2. Image recognition: performs single-image inference on an existing hand photo and outputs the category, maximum similarity and confidence lower bound.
  3. Data capture: captures sample images in the four-cell grid of left/right hand × back of hand / palm, and saves them to disk after labeling the category.
  4. Category management: view the sample count of each category, add / rename / delete categories, browse and delete sample images, and aggregate samples to generate a new category center model.
  5. Activation code verification: locally decode and verify the activation code against the device binding and validity window, with time rollback protection and unlock reset, fully offline.
  6. Parameter settings: hand detection confidence, confirmation frames, camera resolution, recognition confidence lower bound, left/right swap.

1.2 Recognition Pipeline

Real-time / image recognition are chained in three stages:

  1. Hand detection: the hand segmentation model locates the hand box in the frame.
  2. Side classification: the side classification model determines whether the current view is the back of hand or the palm.
  3. Category determination: the image encoder extracts hand features and compares them with the respective category centers of the back of hand / palm, taking the category with the highest similarity; a similarity below the confidence lower bound of that side is judged as "undeterminable".

1.3 Environment Requirements

ItemRequirement
minSdkVersion25
compileSdkVersion33
targetSdkVersion33
Supported ABIarm64-v8a (Rockchip platforms such as RK3576)
Build environmentAGP 7.2.0 / Gradle 7.3.3, NDK 21.4.7075529, JDK 11 bytecode level
Third-party dependenciesNo third-party libraries; only Android system APIs are used (Camera2, org.json, MediaStore)

2. Integration Steps

2.1 Import the AAR

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

2.2 Permission Declaration

The SDK's AndroidManifest.xml already declares the following permissions, which are merged automatically with the integrator's manifest:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="28" />
The camera runtime permission is requested by each camera page on entry; on Android 10+ dataset export goes to the Downloads directory via MediaStore and requires no storage permission.

2.3 Launch Entry

Launch the SDK main menu from any page of the integrator app:

Intent intent = new Intent(context, com.example.handsdetection.MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
The SDK does not require an initialization class to be registered in the Application; recognition models are loaded on demand when the corresponding page is entered.

3. Functional Modules and Entry Pages

The SDK has the following pages registered (fully qualified names); construct an Intent and start them directly.

3.1 Page List

Page classFully qualified package nameFunctionOrientationActivation required
MainActivitycom.example.handsdetection.MainActivityMain menu (entry page)Portrait—
CameraClipActivitycom.example.handsdetection.CameraClipActivityReal-time recognition (hand detection + side classification + category determination)LandscapeYes
ClipTestActivitycom.example.handsdetection.ClipTestActivityImage recognition (single-photo inference)LandscapeYes
DataCollectActivitycom.example.handsdetection.DataCollectActivitySample capture (four-cell capture + category labeling)LandscapeYes
DatasetViewerActivitycom.example.handsdetection.DatasetViewerActivityDataset / category management, model updatePortraitYes
GatewayLoginActivitycom.example.handsdetection.GatewayLoginActivityActivation code verification / unlock resetPortraitNo
SettingsActivitycom.example.handsdetection.SettingsActivityParameter settingsPortraitNo

3.2 Base Classes and Views

ClassPackage nameDescription
CameraActivitycom.example.handsdetection.CameraActivityCamera base class: Camera2 preview, frame callback, single / two-hand flow, common logic for result bits and buttons; DataCollectActivity extends it. Not registered separately in the manifest
OverlayViewcom.example.handsdetection.OverlayViewHand box / status overlay view

3.3 Menu Navigation

Buttons in MainActivity map to the target pages:

Menu buttonTarget page
Real-time recognitionCameraClipActivity
Image recognitionClipTestActivity
Data captureDataCollectActivity
Data category managementDatasetViewerActivity
SettingsSettingsActivity (no activation required)
Activation code verificationGatewayLoginActivity (no activation required)
Before entering protected features, MainActivity.checkActivationStatus() re-checks the activation code locally; if not activated or expired, a prompt is shown and the activation page is opened.

4. Activation Code Mechanism (Local Offline Verification)

4.1 Verification Flow

Activation is local offline decoding and does not depend on an online gateway:

  1. On first entry, a device ID is generated (android_ + ANDROID_ID + 3-digit random suffix) and persisted locally.
  2. After a 24-digit activation code is entered, a digest comparison is performed locally against the device ID, and the activation start / end time window is parsed.
  3. If verification passes, the activation code is saved and the last valid time is updated; otherwise the specific failure reason is returned.
  4. Re-checked every time the user returns to the main page and before entering protected features; if the system time has been rolled back, the entry is blocked with a prompt.

4.2 Activation Code Format

  • After removing hyphens and spaces it is 24 hexadecimal digits ([0-9a-f]).
  • Structure:
SegmentLengthMeaning
0–1516 digitsDigest check part: the first 16 digits of MD5(last 5 chars of device ID + start day hex + end day hex)
16–194 digitsActivation start day (hex day count, GMT+8)
20–234 digitsActivation end day (hex day count, GMT+8)
  • Time window: start day×86400 − 28800 ~ end day×86400 + 86399 − 28800.
  • Special code: the UNLOCK- prefix is an unlock code that clears the local activation code and device ID cache and resets the device number.

4.3 Persistence Keys

SharedPreferencesKeyContent
device_configactivation_codeActivation code saved on this device
device_configdevice_id_v4Device ID of this device
rollback_guardlast_max_wallLast valid timestamp (rollback protection baseline, 5-minute tolerance)

4.4 Public Methods GatewayLoginActivity

com.example.handsdetection.GatewayLoginActivity:

MethodSignatureDescription
verifyActivationCodestatic boolean verifyActivationCode(String input, String deviceId, StringBuilder errMsg, long lastMaxWall)Verifies the activation code; returns true on success, and writes the failure reason into errMsg
decodeActivationSpanstatic String decodeActivationSpan(String input, long lastMaxWall)Decodes the activation start / end dates, valid days and current status (not started / activatable / expired / invalidated), returning multi-line text

Verification failure reasons: wrong length, device mismatch or tampering, abnormal device ID, window not started, past the end date, historical time out of range and invalidated.


5. Recognition Engine YoloDual (JNI Wrapper)

com.example.handsdetection.YoloDual: Java wrapper of the native library libhandsdetection.so, statically loading handsdetection.

5.1 Initialization

MethodReturn valueDescription
nativeInitSegOnly(String segPath)float[]Initializes only the hand segmentation model (camera mode, detection chain not loaded), returns [ret]
nativeInitClsFace2(String face2Path)float[]Initializes the side classification model (palm / back of hand), returns [ret, faceNc]
nativeInitClipDynamic(String clipPath, String[] centerPaths, int[] faceCounts)float[]Initializes the image encoder and dynamic category centers; the order of centerPaths = back-of-hand category centers + palm category centers; faceCounts = [number of back-of-hand categories, number of palm categories]; returns [0 success, model_w, backNc, palmNc]

5.2 Inference

MethodReturn valueDescription
nativeDetectFast(byte[] rgb, int w, int h)float[]Hand detection on the real-time path, returns hand boxes [N, (cls,conf,x1,y1,x2,y2)*N]
nativeClsChain(int which, byte[] rgb, int w, int h)float[]General classification; which=3 is side classification, returns [classIdx, conf]
nativeClipInfer(byte[] rgb, int w, int h, int which)float[]Category determination; which=0 back of hand / 1 palm; returns [bestClass, bestSim, sim0, sim1, ...]
nativeClipExtractFeature(byte[] rgb, int w, int h)float[]Extracts the image feature vector

5.3 Control and Release

MethodDescription
nativeSetMode(int mode)Switches mode: 0 dual model, 1 segmentation only, 2 detection only
nativeSetSegConf(float conf)Adjusts the hand detection confidence threshold at runtime (0~1)
nativeDeinit()Releases native resources

6. Category Model Management ClipModelManager

com.example.handsdetection.ClipModelManager: manages the active category center model (several categories each for back of hand / palm, 512-dimensional center vectors).

6.1 Storage Location

  • Models imported / trained by the user: <files>/clip_model/
  • config.json: category key list per side, display names, threshold configuration
  • back_<key>.bin / palm_<key>.bin: center vectors of each category
  • When no user model exists, the built-in fallback center bins in assets/ are used.

6.2 Public Methods

MethodReturn valueDescription
modelDir(Context ctx)FileCategory model directory
loadCurrent(Context ctx)FaceConfig[]Reads the currently active configuration; returns null if no valid user model exists
importModel(Context ctx, List<String> backKeys, List<String> backNames, List<File> backBins, List<String> palmKeys, List<String> palmNames, List<File> palmBins)booleanSaves a new category model: clears old bins, copies center files, writes config.json, and synchronizes labels.json
defaultBackKeys()String[]Built-in back-of-hand category keys: normal / nail / jewelry / bandage
defaultPalmKeys()String[]Built-in palm category keys: normal / jewelry / bandage
stagingDir(Context ctx)FileImport staging directory (cache/clip_import)
clearStaging(Context ctx)voidClears the staging directory

6.3 FaceConfig Structure

ClipModelManager.FaceConfig:

FieldTypeDescription
faceStringback / palm
keysList\<String\>Category English identifier
namesList\<String\>Category display name
centerFilesList\<File\>Absolute path of the center bin

7. Capture Configuration and Dataset

7.1 CaptureConfig

com.example.handsdetection.CaptureConfig: capture side / left-right hand / category definitions and on-disk path rules.

Fixed four-cell definition (2×2):

CellSidePosition
0Back of handTop left (left back of hand)
1Back of handTop right (right back of hand)
2PalmBottom left (left palm)
3PalmBottom right (right palm)
MethodReturn valueDescription
labelsFile(Context ctx)FilePath of labels.json (<files>/labels.json)
loadLabels(Context ctx)voidLoads categories from labels.json; writes default categories if it does not exist
saveLabels(Context ctx, Map<String,List<String>> labels, Map<String,String> names)voidSaves category keys and display names
labelsOf(Context ctx, String face)List<String>Gets the category key list of one side
labelName(Context ctx, String label)StringCategory display name (English suffix stripped)
builtinName(String label)StringBuilt-in Chinese names: normal 正常 / nail 美甲 / jewelry 首饰 / bandage 创可贴
faceName(String face)Stringback→手背,palm→手心
sideName(String side)Stringleft→左手,right→右手
sideOfCell(int cell, boolean swapLR)StringLeft/right hand corresponding to the cell (affected by left/right swap)
cellName(int cell, boolean swapLR)StringCell display name, e.g. "左手背"
captureRoot(Context ctx)FileCapture root directory: <externalFiles>/Capture_asset/1

7.2 HandDatasetSaver

com.example.handsdetection.HandDatasetSaver: sample saving and statistics.

MethodReturn valueDescription
HandDatasetSaver(Context ctx)ConstructorBinds the capture root directory, creates directories and refreshes counts
getRoot() / getRootDisplay()File / StringCapture root directory
refreshCounts()voidRescans the directory to refresh the count of each category
count(String face, String label)intNumber of images of a category on one side
count(String face, String side, String label)intNumber of images of a category for one hand on one side
sideTotal(String face, String side)intTotal number of images for one hand on one side
total()intTotal number of samples
save(String face, String side, String label, Bitmap full, Bitmap crop, ...)Saved to diskSaves the full image / cropped image and writes metadata
writeSummary()voidWrites the summary CSV

On-disk structure: images are stored in {face}/{label}/, and meta/labels.csv records metadata (time, side, category, left/right hand, sequence, confidence, file name, etc.).

7.3 DatasetExporter

com.example.handsdetection.DatasetExporter:

MethodReturn valueDescription
export(Context ctx, File root)StringRecursively packs the capture directory into a zip in the Downloads directory (uses MediaStore.Downloads on Android 10+), returning the save path with a file count / size hint

8. Settings Items

com.example.handsdetection.Settings: SharedPreferences persistence, storage name yolo_settings.

KeyMethodDefault valueDescription
seg_confgetSegConf / setSegConf0.80Hand detection confidence (higher is stricter)
valid_framesgetValidFrames / setValidFrames2Number of consecutive correct frames required for confirmation (1~10)
resolutiongetResolution / setResolution640x480Camera capture resolution
clip_thr_backgetClipThrBack / setClipThrBack0.70Confidence lower bound for back-of-hand category determination
clip_thr_palmgetClipThrPalm / setClipThrPalm0.70Confidence lower bound for palm category determination
capture_swap_lrgetSwapLR / setSwapLRfalseLeft/right swap on the capture page (left of the frame = right hand)
After changing the hand detection confidence, confirmation frames or resolution, return and re-enter "Real-time recognition" for it to take effect; if the camera cannot be opened, switch back to a 4:3 resolution such as 640x480.

9. Built-in Files

9.1 Built-in AI Models (AAR assets/)

FilePurpose
hand_seg.rknnHand segmentation / hand detection
hand_cls.rknnPalm / back-of-hand side classification
mobileclip_image_encoder_rk3576.rknnHand image feature encoder
back_normal.binBack of hand - normal category center
back_jewelry.binBack of hand - jewelry category center
back_bandage.binBack of hand - bandage category center
palm_normal.binPalm - normal category center
palm_jewelry.binPalm - jewelry category center
palm_bandage.binPalm - bandage category center
jpg/test.jpgBuilt-in test image for image recognition
Models are packaged with the AAR and released to the cache directory by copyAssetToCache when entering a recognition page, then loaded; .rknn / .bin resources are not compressed when packaged. New models trained by the user in category management are stored in <files>/clip_model/ and take precedence over the built-in fallback models.

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

FileDescription
libhandsdetection.soLocal inference library compiled from cpp/native-lib.cpp via CMake (hand detection / side classification / encoder post-processing / NMS)
librknnrt.soRKNN platform runtime library (precompiled, shipped with the package)

9.3 Runtime Generated Directories

PathContent
<files>/clip_model/Category center models imported / trained by the user and config.json
<files>/labels.jsonActive category keys and display names
<externalFiles>/Capture_asset/1/Captured sample images and meta/labels.csv
<cache>/Temporary model release directory, import staging clip_import, temporary dataset export zip

10. Notes and FAQ

  1. ABI and platform: the native library is arm64-v8a only and targets Rockchip RK3576-class platforms; other architectures / devices cannot run inference.
  2. Models loaded on demand: recognition models are initialized when the corresponding page is entered, and the first load takes a short time; native resources should be released after leaving the page.
  3. Thread requirements: inference runs on the camera analysis thread / background thread; do not make time-consuming inference calls on the main thread.
  4. Category centers are replaceable: when replacing the category library, the back-of-hand / palm center bins must be in the same order as the category keys; the confidence lower bound must be adjusted to match the new category library.
  5. Capture and training are separate: captured samples are saved to disk first, and the new samples are aggregated into the active category model only after "Save data and train model" is executed on the category management page.
  6. Activation works offline: activation codes are verified locally without network access; the device ID is bound to the activation code, and a new one must be requested after changing devices or clearing the cache.
  7. Time rollback protection: the last valid time is recorded on the device; if the system time is rolled back beyond the tolerance window, the entry is blocked. Correcting the time or entering a renewal activation code restores access.
  8. Keep the package name unchanged: the SDK keeps its original package name com.example.handsdetection; integrators must not change the package or rename classes, otherwise the resource R class and references will break.
  9. Resolution compatibility: if the camera cannot be opened at some high resolutions, switch back to a 4:3 specification such as 640x480 on the settings page.

11. Class and Package Name Reference

11.1 Business Pages

ClassFully qualified package namePurpose
MainActivitycom.example.handsdetection.MainActivityMain menu entry
CameraClipActivitycom.example.handsdetection.CameraClipActivityReal-time recognition page
ClipTestActivitycom.example.handsdetection.ClipTestActivityImage recognition page
DataCollectActivitycom.example.handsdetection.DataCollectActivitySample capture page
DatasetViewerActivitycom.example.handsdetection.DatasetViewerActivityDataset / category management page
GatewayLoginActivitycom.example.handsdetection.GatewayLoginActivityActivation code verification page
SettingsActivitycom.example.handsdetection.SettingsActivitySettings page
CameraActivitycom.example.handsdetection.CameraActivityCamera base class (extended by the capture page, not registered separately)
OverlayViewcom.example.handsdetection.OverlayViewBox overlay view

11.2 Engine / Data / Configuration

ClassFully qualified package namePurpose
YoloDualcom.example.handsdetection.YoloDualNative inference JNI wrapper
ClipModelManagercom.example.handsdetection.ClipModelManagerCategory center model management / import
CaptureConfigcom.example.handsdetection.CaptureConfigCapture side / hand / category and path rules
HandDatasetSavercom.example.handsdetection.HandDatasetSaverSample saving and statistics
DatasetExportercom.example.handsdetection.DatasetExporterDataset packing and export
Settingscom.example.handsdetection.SettingsParameter preference persistence

Appendix: Artifacts and Build

ItemDescription
Debug artifacthands-sdk/build/outputs/aar/hands-sdk-debug.aar
Module source directoryhands-sdk/src/main/
Module build scripthands-sdk/build.gradle
Native build scripthands-sdk/CMakeLists.txt
Debug build command./gradlew :hands-sdk:assembleDebug
Release build command./gradlew :hands-sdk:assembleRelease
SDK namespacecom.example.handsdetection (same as the resource R class package name)