Exploring the Android NDK

I have been testing the Android development tools. From what I have learned, the tools are separated into two main products: the Android Software Development Kit (SDK) and the Android Native Development Kit (NDK).

The SDK was the first development toolkit for Android, and it only allowed applications to be written using the Java programming language. The NDK was released some time later as a toolchain to enable developers to write parts of their applications using native programming languages (C and C++).

One of the first programs I developed to get a feeling of what the Android SDK looked like was an OpenGL ES App that painted the background using a color degrade. I wrote it a couple of months ago, but today was the first time I ran it on a real Android device.

The resulting image can be seen in the following picture:

Android OpenGL ES Test

Other than trying the SDK, what I really wanted to do was to experience how hard it would be to rewrite part of the App in C and then having both integrated. It turns out adding components built using the NDK is not very hard (for pure C code), so I decided to try moving all the rendering code to a plain C function.

I started a new project and coded all the rendering logic in a C function that I called “render“. Then, the NDK was used to compile the C code into a JNI-compliant shared library and, finally, I wrote a simple Java wrapper that calls into the shared library’s render function to do all the drawing.

The wrapper is responsible for creating the Android “Activity”, setting up an OpenGL ES context, and calling the native C function. The native C function clears the background and does all the drawing.

Getting all the JNI requirements in place in order to have the Java runtime recognize the native library and call a native method was not too hard, but it was not trivial either. It is definitely much more complicated that calling native libraries from Objective-C or even Python. After a few tries, the bond was made:

Android OpenGL ES rendering from C code.

Clearly this is a very simple example where the C code could be tailored to fit JNI’s requirements from the start. I expect porting an existing C++ codebase to be much more difficult. However, I am looking forward to continue delving into Android’s development tools.