0 Flares 0 Flares ×

Google’s Android NDK is a great toolset for developers who need to integrate C/C++ code with their Android apps. The NDK uses the Java Native Interface (JNI) to provide a bridge between Java and native C/C++ code, while also providing many common C libraries and APIs to build upon. On top of this, the NDK also guarantees forward ABI compatibility with various versions of the ARM instruction set, meaning your native code will run on any Android device that implements the instruction set that your app is built against. The NDK is in fact the preferred way that games (using OpenGL) and other high-performance or hardware level code should be implemented. The latest NDK r5 even ships with support for Native Activities, Sensors, Windows, Surfaces, Event Loops, OpenSL Audio, STL, and more.

In short, the Android NDK is an exciting and compelling lower level of integration for Android apps — but how do you make use of all the native goodness in a Titanium app? Specifically, how do you expose native C/C++ code to Javascript?

Starting with Titanium Mobile 1.5, our Android support comes with a new Module API that allows our developers to expose Java code to Javascript. That’s half the battle, but we still need to make the leap from Java to C/C++ over JNI, and we need to figure out how to distribute and package the final native libraries with our app. Last week I pushed some changes that allow Titanium developers to easily include and build native libraries for inclusion in their apps or modules. Before this change, you were required to essentially re-package and re-sign your APK every time you wanted a shared library to be included with your Titanium app.

Here’s a brief outline of the new NDK support for Titanium Android modules/apps:

  • Modules have 2 new properties that are supported in the top level “build.properties” file. These properties enable automatic ndk-build when “ant” is used to build the module:
    • module.ndkbuild=true
    • android.ndk=/path/to/ndk
  • Under the “jni” folder of your module project, place your C/C++ source and Android.mk file
  • Native libraries (.so) are automatically included in the zip of your Android module under “dist”, and any Titanium app that uses your module will automatically import the native library correctly into the final APK

DISCLAIMER: Our NDK support will still be beta for our upcoming 1.6 release, we hope to finalize it for 1.7.

What follows is a quick video that shows how I integrated some simple C code into a Titanium Android module, and used it inside a Titanium app:

Here’s some links for programming against the NDK that might also be helpful: JNI Reference Android NDK page