Integrate native code with the NDK

The Native Development Kit (NDK) APIs enable you to write an Android Things app
purely in C/C++ or extend a Java-based Android Things app with C or C++ code.
You can use these APIs to port existing drivers and apps written for other
embedded platforms.

Getting started with the NDK

If you've never used the NDK, see the Android NDK Getting
Started guide to download and install the
NDK. The documentation also has detailed information on how to use the NDK.

Get the Android Things native library

The native peripheral I/O APIs are available in the Android Things native
library. You
will need these APIs to communicate with sensors, actuators, and other
peripherals using industry standard protocols and interfaces.

Copy the entire directory into the root directory of the Android Studio new
project template. The directory structure looks like this:

libandroidthings/
${ABI}/
include/
pio/
*.h
lib/
libandroidthings.so

You'll include the header files in the include/pio directory to compile your
app and link the libandroidthings.so shared object for the appropriate
application binary interface (ABI), for example, x86, when you package your app.
The
FindAndroidThings.cmake
CMake module file is also available to help you configure new NDK projects to
use the Android Things native library.

See the header files for the library in the GitHub
repository
for more information and documentation.

Packaging native code

Android Things apps are bundled with the system image and are read-only at
runtime. This requires that binary assets like native shared libraries are read
directly from the APK instead of being extracted at install time. Apps that
include NDK code must set the
extractNativeLibs
attribute to false in their manifest file for proper compression, packaging,
and alignment of the libraries within the APK:

Caution: You will be unable to upload your APK to the
Android Things Console if it contains native code
without this attribute.Note: Your app may indirectly include native code from library dependencies
(such as TensorFlow Lite) or
cross-platform frameworks (such as Go on Mobile).
Be sure to include this attribute in these cases as well.

Native PIO APIs

The native Peripheral I/O (PIO) APIs let you write C/C++ code to control GPIO,
PWM, I2C, SPI and UART peripherals that access the same underlying
peripheral service as the standard Peripheral I/O
APIs.