You are on page 1of 8

Android NDK

(1) What is the Android NDK?


The Android NDK(Native Development Kit) provides tools that allow Android application developers to embed components that make use of native code in their Android applications. Android applications run in the Dalvik virtual machine. The NDK allows developers to implement parts of their applications using native-code languages such as C and C++. This can provide benefits to certain classes of applications, in the form of reuse of existing code and in some cases increased speed. The NDK provides: A set of tools and build files used to generate native code libraries from C and C++ sources A way to embed the corresponding native libraries into application package files (.apks) that can be deployed on Android devices A set of native system headers and libraries that will be supported in all future versions of the Android platform, starting from Android 1.5 Documentation, samples, and tutorials This release of the NDK supports the ARMv5TE machine instruction set and provides stable headers for libc (the C library), libm (the Math library), the JNI interface, and other libraries. Please note that the NDK does not enable you to develop native-only applications. Android's primary runtime remains the Dalvik virtual machine.

(2)

Contents of the NDK


Developement tools The NDK includes a set of cross-toolchains (compilers, linkers, etc..) that can generate native ARM binaries on Linux, OS X, and Windows (with Cygwin) platforms. It provides a set of system headers for stable native APIs that are guaranteed to be supported in all later releases of the platform: libc (C library) headers libm (math library) headers JNI interface headers libz (Zlib compression) headers liblog (Android logging) header A Minimal set of headers for C++ support

The NDK also provides a build system that lets you work efficiently with your sources, without having to handle the toolchain/platform/CPU/ABI details. You create very short build files to describe which sources to compile and which Android application will use them the build system compiles the sources and places the shared libraries directly in your application project. Important: With the exception of the libraries listed above, native system libraries in the Android 1.5 platform are not stable and may change in future platform versions. Your applications should only make use of the stable native system libraries provided in this NDK.

(3)

Purpose
The first release of the ndk (available in 1H2009) will be targeted towards Java application developers who wish to write native code shared libraries to access native code APIs or accelerate portions of their application. The NDK comes as an add-on for the Android SDK, and is not meant as a substitute development platform. Meaning that the developer will not be able to code an application for Android entirely in C / C++. However it is meant as a tool to create or port libraries which can be utilized by your main program (written in Java using the SDK). Highly CPU intensive tasks stand most to gain by being written in native code. Why might someone want to write and run their own native code? These are few of the reasons. To improve the performance of time or space sensitive operations To port existing code To gain access to hardware resources or libraries not available from JAVA

(4)

Risks
There is no guarantee that the applications would work on future phones. The existing native libraries (that you need to link with) on the current Android phones are mainly the same. No phone OEM has ventured beyond the standard android configuration. However, given time, the libraries would change, diverge and in the worst case, Android would even be based on different architecture/platforms causing the developer to ship different native libraries themselves. They are affectively using undocumented APIs that can break on some phones or possibly when the phone firmware is upgraded.

(5)

Pros
The companies can port their existing code to Android OS. Many applications have large amounts of their business logic wrapped up in c++ or more commonly c so it can be compiled on any platform. Developers can use NDK to code some of the sensitive parts of their programs in C, followed by reusing existing C code on the Android platform Android applications run in the Dalvik virtual machine, but the new NDK will allow developers to call native code in such a way that they can create high-performance applications running directly on Android's Linux base. Large no of libraries which already exist written in C / C++, can now easily be ported to run on Android. certain Developers can utilize the opportunity of ready-made code in the new platform. The code generated by compiling directly will run faster than code for Dalvik. Some instances there will be less allocated memory and increased performance in applications.

(6)

Cons
Doesnt let developers to run entirely native codes over devices, but allows them to add native codes into applications designed to run in Dalvik virtual machines (DVM). The NDK doesnt offer access to platform framework APIs, and it is tailored to be used along with Java to code some crucial parts of programs that need current C libraries. Will be not be compatible with Android devices which use different processors unless they have been recompiled for each processor. Currently the NDK only supports the ARMv5TE instruction set. NDK based applications will be harder to debug. The Applications will be more complicated

(7)

When to use an when not to use


Using the NDK will not be relevant for all Android applications. As a developer, he/she will need to balance its benefits against its drawbacks, which are numerous! the application will be more complicated, have reduced compatibility, have no access to framework APIs, and be harder to debug. That said, some applications that have selfcontained, CPU-intensive operations that don't allocate much memory may still benefit from increased performance and the ability to reuse existing code. Some examples are signal processing, intensive physics simulations, and some kinds of data processing." Simply re-coding a method to run in C usually does not result in a large performance increase. The NDK can, however, be an effective way to reuse a large corpus of existing C/C++ code.

(8)

System and Software Requirements


This section below describes the system and software requirements for using the Android NDK, as well as platform compatibility considerations that affect appplications using libraries produced with the NDK. The Android SDK A complete Android SDK installation (including all dependencies) is required. Android 1.5 SDK or later version is required. Supported operating systems Windows XP (32-bit) or Vista (32- or 64-bit) Mac OS X 10.4.8 or later (x86 only) Linux (32- or 64-bit, tested on Linux Ubuntu Dapper Drake) Required development tools For all development platforms, GNU Make 3.81 or later is required. Earlier versions of GNU Make might work but have not been tested. You can check this by running 'make -v' from the command-line. For Windows, a recent release of Cygwin, including both the gmake and gcc packages, is required.

(9)

Installing the NDK


To install the NDK, follow these steps: 1. Download appropriate NDK package for your development computer(based on your OS). 2. Uncompress the NDK download package using tools available on your computer. When uncompressed, the NDK files are contained in a directory called android-ndk-<version>. You can rename the NDK directory if necessary and you can move it to any location on your computer. This documentation refers to the NDK directory as <ndk>. 3. Open a terminal, change to the NDK directory, and run the host-setup script. The script sets up your environment and generates a host configuration file used later, when building your shared libraries. The path to the host-setup script is:

<ndk>/build/host-setup.sh If the script completes successfully, it prints a "Host setup complete." message. If it fails, it prints instructions that you can follow to correct any problems. 4. If a error pops up, use following command:
<ndk>bash ./build/host-setup.sh

Once you have run the host-setup script, you are ready start working with the NDK.

(10) Steps for using NDK


To use the NDK, follow these steps: 1) Create a .java file in a particular directory. 2) This .java file decalres all the native functions for which corresponding JNI layer has to be written. 3) Inside .java file specify package like "package com.example;". 4) Create directory hierarchy same as package mentioned in previous step. Ex:- HelloNdk.java package com.example.HelloNdk; class HelloNdk { public native String dataFromJNI(); public native int fun2(); } 5) for ex- com.example implies that we need to have the java source file and the associated class file in the directory com/example. 6) Put .java file in the last directory mentioned in the package.

7) Compile .java file using following command: ex:- javac com/example/file_name.java javac com/example/HelloNdk.java 8) Generate Header file using following command: ex:- javah -o file_name.h com/example/filename javah -o HelloNdk.h com/example/HelloNdk HelloNdk.h /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_example_HelloNdk */ #ifndef _Included_com_example_HelloNdk #define _Included_com_example_HelloNdk #ifdef __cplusplus extern "C" { #endif /* * Class: com_example_HelloNdk * Method: dataFromJNI * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_example_HelloNdk_dataFromJNI (JNIEnv *, jobject); /* * Class: com_example_HelloNdk * Method: fun2 * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_example_HelloNdk_fun2 (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif

9) Write .c file(JNI file) by taking method definitions from .h file that is generated in last step. 10) In this .c file all the native functions declared in the .h file has to be defined(JNI layer). 11) IN addition to all the native function we need to have one more function in JNI to load itself in JVM viz JNI_OnLoad. In the .c file add following code: JNIEXPORT jint JNICALL JNI_OnLoad (JavaVM * vm, void * reserved) { return JNI_VERSION_1_6; }

12) The above steps completes the JNI layer. In the example above we have named the JNI file to be hello-ndk.c hello-ndk.c #include <string.h> #include <jni.h> JNIEXPORT jstring JNICALL Java_com_example_HelloNdk_dataFromJNI ( JNIEnv* env,jobject thiz ) { return (*env)->NewStringUTF(env, "hi, I am coming from jni "); } JNIEXPORT jint JNICALL Java_com_example_HelloNdk_HelloNdk_fun2 ( JNIEnv* env,jobject thiz ) { return 0; } JNIEXPORT jint JNICALL JNI_OnLoad (JavaVM * vm, void * reserved) { return JNI_VERSION_1_6; } 13) Go to your Android_NDK root directory. 14) Make your own directory inside /sources/samples. 15) Put all your source files(.c) viz JNI layer files our case hello-ndk.c. 16) Create one Android.mk file here. ex:- sample file is as follows: LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := hello-ndk LOCAL_SRC_FILES := hello-ndk.c include $(BUILD_SHARED_LIBRARY) 17) LOCAL_MODULE flag mentions the name which it to be generated for the shared object. 18) Again go to your Android_NDK root directory. 19) Create one directory(with the same name as in /sources/samples) inside /apps directory. 20) Create one Application.mk file here. ex:- sample file is as follows: APP_PROJECT_PATH := $(call my-dir) APP_MODULES := hello-ndk 21) See to it that values given to APP_MODULES and LOCAL_MODULE are matching.

22) If you are going to use some other .a file, then from NDK root directory go to /build/toolchains/arm-eabi-4.2.1 directory. 23) Open setup.mk file and put the path to your .a file in TARGET_LDLIBS macro. ex:- TARGET_LDLIBS := -Wl,/home/nativelibs/libnative.a -Wl,-rpathlink=$(SYSROOT)/usr/lib $(TARGET_LIBGCC) 24) Again go to your Android_NDK root directory. 25) Run following command to generate .so file make APP=<yourapp> ex:- make APP=hello-ndk 26) Create Android aplication with the same package name as specified in .java(step 2) file. 27) The application which finally uses the shared object must declare the native functions in the original format specified and not in the signature generated by the javah tool. 28) The application can include the shared native library by calling System.loadLibrary(file_name). Ex:- Android application sample package com.example; import com.example.R; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class HelloNdk extends Activity { /** Called when the activity is first created. */ int i; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.tv01); tv.setText( dataFromJNI() ); int i = fun2(); } public native String dataFromJNI(); public native int fun2(); static { System.loadLibrary("hello-ndk"); } }

29) Put .so file inside /system/lib from tools directory of Androi_SDK or using DDMS tool in eclipse. ex:- abd push <path-to-.so-file>/file_name.so /system/lib 30) It may be the case that /system/lib is a read-only memory in that case do the following: Make the /system/lib to be read-write by the command adb shell mount -o remount rw /system 31) Run your Android application.

You might also like