Overview
NNAPI is a C API that serves as a bridge between your application and hardware accelerators like GPUs, DSPs, and dedicated neural network processors.Key benefits
- Hardware acceleration - Automatically uses the best available hardware accelerator
- Reduced latency - On-device inference eliminates network round trips
- Privacy - Data stays on device
- Offline support - Works without internet connectivity
NNAPI is available starting from Android 8.1 (API level 27), with significant improvements in subsequent releases.
Getting started
1
Add NNAPI to your build
In For ndk-build, in
CMakeLists.txt:Android.mk:2
Include the NNAPI header
3
Check NNAPI availability
Building a neural network model
Create the model
Define model operations
Specify model inputs and outputs
Executing inference
Create compilation
Performance preferences
ANEURALNETWORKS_PREFER_LOW_POWER- Optimize for battery lifeANEURALNETWORKS_PREFER_FAST_SINGLE_ANSWER- Optimize for low latencyANEURALNETWORKS_PREFER_SUSTAINED_SPEED- Balance performance and power for repeated inference
Run inference
Using TensorFlow Lite with NNAPI
TensorFlow Lite provides a higher-level API with NNAPI delegation:Setup
Inbuild.gradle:
Load and run model
TensorFlow Lite automatically falls back to CPU execution if NNAPI is unavailable or doesn’t support certain operations.
Hardware acceleration
Query available accelerators
Specify execution device
Optimizing models for NNAPI
Use supported operations
Not all operations are hardware-accelerated. Check the NNAPI operator support for your target API level.Quantization
Quantize models to 8-bit integers for better performance:Input preprocessing
Perform preprocessing (normalization, resizing) efficiently:Error handling
Best practices
- Reuse compilations - Compile once, execute many times for better performance
- Batch processing - Process multiple inputs in a single inference when possible
- Quantize models - Use 8-bit quantization for faster execution and smaller model size
- Profile on target devices - Performance varies significantly across device accelerators
- Provide CPU fallback - Not all operations are supported on all accelerators
- Cache compiled models - Save compilation results to disk to reduce startup time (Android 10+)
- Test API level support - Use feature detection, not just API level checks
Debugging and profiling
Enable verbose logging
Benchmark performance
Additional resources
- NNAPI Reference - Official API documentation
- Neural Networks API Guide - Comprehensive developer guide
- TensorFlow Lite - High-level ML framework with NNAPI support
- Model optimization - Techniques for faster inference