Sei sulla pagina 1di 8

1/15/2011

Android Beginners: NDK Setup Step by

Android Beginners: NDK Setup Step by Step


Jul 6th, 2010 at 5:18 pm Most Android developers start their learning from pure Java, Android SDK bas ed apps. While everyone is aware that there is the NDK (the Native Development Kit), they dont face the need to us e it. Since NDK is dis tributed separately from the SDK, including documentations and samples, you are not likely to get familiar with NDK before you actually try it as a s olution to one of your development challenges.

12
tweets

retw eet

Becaus e of that, many people think of NDK as of black magic of Android development. Many developers who are not familiar with NDK think it is 1) complex to understand and use, and at the s ame time a lot of developers will think it is a s ort of a 2) silver bullet that can solve any problem that cant be solved with SDK. Well, both opinions are rather wrong, as I hope to show further in this post. Although it does have a maintenance cost and does add technical complexity to your project, NDK is not difficult to install or use in your project. And, while there are cases where NDK will be really helpful for your app, NDK has a rather limited API thats mostly focused on s everal performancecritical areas, such as : OpenGL, including support for some newer vers ions that the (Java) SDK supports Math (some, but not all, calculation-intensive algorithms might benefit from being done on the native layer) 2D graphics pixelbuffer s upport (only starting with 2.2) libc its there for compatibility and perhaps to allow you to port existing native code In this tutorial we will take our basic Android development environment that we created in one of the previous articles and add NDK support to it. We will also create a basic skeleton project that uses NDK that you can us e as the foundation for your NDK-powered apps . The downloads that are necessary for the initial configuration of the environment might take s ome time (around 30 minutes total), so be prepared. Ready? Lets go!

Step 1: Installing C/C++ Support on Eclipse


This is where we stand right after were done with the previous tutorial. In s hort, we have a bas ic Eclipse installation, plus Android SDK and ADT that brings Android support to Eclipse:

(were not going to use our old project, foobar, so you can just close it.) While NDK supports both C and C++, C++ support is rather limited. For example, exceptions are not supported and there are some known bugs in static constructor/des tructor invocations . Also, most of the time when you will us e NDK as it was intended for moving the most performance-critical parts of code to the native layer you are not likely to need much OOP abs traction and other design goodies . What Im trying to say is that NDK code is more likely to be written in C rather than C++. Anyway, our Eclipse installation does not s upport either C or C++ right now. We dont really need the full s upport, including building etc. But we would like to have syntax coloring and basic syntax checking. Thus we have to add some Eclipse features via the update mechanism, almost like when we added Android support. Right now go to Help Install New Software menu item. Choose Galileo as the update site (Work with). Let the item tree load, and check Eclipse C/C++ Development Tools in the Programming Languages branch:

mindtherobot.com//android-beginners

1/8

1/15/2011

Android Beginners: NDK Setup Step by

Then press Next. Say yes to everything, accept the licenses and let Eclips e finish the update. Once it is done, you will see the prompt to res tart Eclips e:

Say Yes and wait for Eclipse to restart. You have C/C++ support in your Eclipse IDE now.

Step 2: Installing Cygwin


Android is Linux bas ed, and thus it is no surprise that when you build native code for it, you need some Unix tools. On Windows , NDK s upports Cygwin 1.7.x and above. If you dont know what Cygwin is, its just a s et of s oftware that emulates Unix environment on Windows which is necessary in some cases, including ours. In order to get Cygwin, go to cygwin.com:

Theres a small grey box on the right s ide of the page that s ays Install or update Cygwin now!. Click it, and Cygwins setup.exe will download and run:

Choose Install from Internet, then click Next, then choose the ins tallation directory (be sure to choose a directory path that contains no spaces in it) and by the way, the whole thing is going to require up to few gigs of s pace. Then, choose the

mindtherobot.com//android-beginners

2/8

1/15/2011 Android Beginners: NDK Setup Step by local package directory just use some temporary directory, youre not likely to need it afterwards .
At this point Cygwin will connect to its central site and download the lis t of mirror sites. Choosing a mirror site that looks geographically close to you may save you s ome download time:

After you choose the mirror and click Next, Cygwin will download and present to you the list of available packages:

By default, only the base packages are installed. We, however, need the development packages . Rather than picking the packages we think we need, and then struggling with mis sing dependencies and other typical Unix nightmares, I s uggest that we install the entire Devel branch. Click (once) on the word Default next to the root Devel node and wait few seconds while the setup hangs. When it is back, you will see that Default changes to Install for the Devel node, jus t like on the screens hot above. Now click next and let Cygwin download the packages and install the environment:

This might take a while, so you can go have a coffee now. Or lunch if your internet connection is s low. When you are back, you will hopefully see the final setup s creen:

mindtherobot.com//android-beginners

3/8

1/15/2011 Android Beginners: NDK Setup Step by Allow it to create an icon on the desktop. Heres what you will s ee on your des ktop after you click Finish an icon that launches the Cygwin cons ole:

Click it once, let the Cygwin console s tart up and initialize:

To check that we have the tool that is important for Android NDK, type make -v in the console:

You should s ee the same res pons e that tells us that GNU Make is pres ent in our Unix environment that is emulated by Cygwin. Cool! Note: From my own experience, Cygwin ins tallation is often unstable and can be error-prone. If you have a s pecific is sue, lets discus s it in comments and Ill try to help. Dont go further if something is wrong at this step, since correctly ins talled Cygwin is a requirement for working with NDK on Windows.

Step 3: Installing the Android NDK


Our next step is to download Android NDK itself and place it on our filesystem. You can get NDK from the official Android

mindtherobot.com//android-beginners

4/8

1/15/2011 site:

Android Beginners: NDK Setup Step by

Download the NDK zip for Windows and extract it somewhere, but again, be s ure that there are no spaces in the path. In my case, I extracted it to C:\, so the path is C:\android-ndk-r4. Now we have the environment ready for our first NDK app!

Step 4: Making a Basic NDK App


The general idea of us ing NDK in apps is to put your native pieces of code into libraries that you can then consume from the Java code. Thus, you always s tart with a standard (Java) app and then add NDK pieces to it. Thus, lets create a bas ic app in Eclipse as we did previous ly, using the New Android Project wizard:

There is , however, an important thing to check, and believe it or not, it is spaces in the path again. My Eclipse workspace is located in a directory that has spaces in it, s o I had to uncheck the Use default location checkbox and manually choose a path that does not have spaces , as you can see in the screenshot above. In general, its better to keep Eclipse workspaces located in s pace-free paths. Otherwise, there are no NDK-s pecific things you should do when creating the app. I allowed the wizard to create a dummy activity called NdkFooActivity that we will use later on. After the app has been created by the wizard

..Make a folder called jni in the root of the project (right-click the project node, New Folder). Create a file called Android.mk (New File) within that folder with the following contents : ?

1LOCAL_PATH := $(call my-dir) 2


mindtherobot.com//android-beginners 5/8

1/15/2011

Android Beginners: NDK Setup Step by

3include $(CLEAR_VARS) 4 5# Here we give our module name and source file(s) LOCAL_MODULE := ndkfoo 6LOCAL_SRC_FILES := ndkfoo.c 7 8include $(BUILD_SHARED_LIBRARY) 9
Except the module name (ndkfoo), treat everything in that file as magic. You can go deeper into Unix Makefiles later if you want. The Android.mk file is important for the NDK build proces s to recognize your NDK modules. In our case we named our module ndkfoo and told the build tool that it consists of one source file named ndkfoo.c. Lets create it in the s ame jni folder:

Heres the content for you to copy and paste: ?

1#include <jni.h> 2 3jstring 4Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* 5env, jobject javaThis) { 6 return (*env)->NewStringUTF(env, "Hello from native code!");
}
Android actually uses the s tandard Java way to communicate with native code called JNI (Java Native Interface). It defines conventions and mechanisms that Java code and C/C++ code use to interact. You can read more about JNI in the official Sun docs, but for now you might notice that the name of the C function is not just random it matches the Java class name. In addition, what the function does is it uses the JNIEnv object to create a Java string from a literal, and returns the string to the caller. You will need to learn more JNI if youre going to use NDK a lot. By the way, it is also possible to call Java methods from native code, create custom objects and s o on. Now, in order to create a binary library from the C s ource that we wrote, we will us e a combination of Cygwin and Android NDK tools. Launch the Cygwin console and us e the cd command to go directly to the folder where your project is. Notice that Windows drives are mapped under /cygdrive within the emulated Unix environment you work with in the Cons ole console. In my cas e, the command line is: cd /cygdrive/c/projects/ndkfoo Then, iss ue a command that will invoke the NDK build tool. In my cas e, since NDK is installed in C:\ it looks like this: /cygdrive/c/android-ndk-r4/ndk-build Heres a s creenshot for you to check:

#include <string.h>

mindtherobot.com//android-beginners

6/8

1/15/2011

Android Beginners: NDK Setup Step by

As you can notice, a successful run of the ndk-build tool will create an .so file in a new folder called libs that will be created in your project root (if its not there yet). The .so file is the binary library that will be included into the application .apk package and will be available for the Java code of the app to link to. You jus t need to hit F5 in Eclips e after selecting the project root to update the Eclips e project with the changes you did in the Cygwin console. You have to repeat the ndk-build command every time you modify the C/C++ source of your NDK code. Eclipse ADT does not support NDK s o you need to do it from the Cygwin cons ole. Dont forget to refresh Eclips e every time! Anyway, the NDK part is actually finis hed. What we need to do now is to change the Java code of the NdkFooActivity clas s to use the NDK code: ?

01 02package com.mindtherobot.samples.ndkfoo; 03 04import android.app.Activity; 05import android.app.AlertDialog; 06import android.os.Bundle; 07 08public class NdkFooActivity extends Activity { 09 10 // load the library - name matches jni/Android.mk 11 static { System.loadLibrary("ndkfoo"); 12 } 13 14 // declare the native code function - must match ndkfoo.c 15 private native String invokeNativeFunction(); 16 17 @Override public void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.main); 20 21 // this is where we call the native code 22 String hello = invokeNativeFunction(); 23 24 new AlertDialog.Builder(this).setMessage(hello).show(); 25 } 26} 27
As you can probably guess , this code will invoke the NDK method that will return the string, that will be displayed as an alert on the screen. Heres the res ult of running the ndkfoo app on the emulator:

mindtherobot.com//android-beginners

7/8

1/15/2011

Android Beginners: NDK Setup Step by

Congratulations! Your first NDK app is running fine.

Step 5: Be Wise and Careful


As it was mentioned above, and as you probably understand better now, NDK is not a monster and is quite easy to use in your app. However, every time you want to use NDK, pleas e think twice and perform inves tigation to s ee how much you could actually gain from using it. Mixing C/C++ with Java is generally a bad idea from the code quality point of view, and Dalvik VM is getting faster and faster so you can avoid the NDK in many cases . Also, be s ure to read the NDK docs and learn JNI thoroughly to make s ure you us e NDK correctly and s afely.

mindtherobot.com//android-beginners

8/8

Potrebbero piacerti anche