Chapter  2

Getting Started With the NDK

The Android Native Development Kit (NDK) is a companion to the SDK and is what you use when you want part or all of your Android application to use native code. While bytecode needs to be interpreted by a virtual machine, native code can be directly executed by the device's processor without any intermediate step, making execution faster, and sometimes much faster. The Dalvik Just-In-Time (JIT) compiler is compiling the bytecode into native code, making your applications faster by having to interpret the code less often (and ideally, only once) since it will use the native code it generated whenever it is available. When you use the NDK, the compilation into native code occurs on your development environment and not on the Android device. You may be wondering why you would need to worry about the NDK since the Dalvik JIT compiler can generate native code dynamically and therefore you could write your application in Java using the SDK. This chapter covers the reasons why you may need to use the NDK and the various ways to use it.

There are essentially two ways to use native code and the NDK:

  • You can write one part of your application in Java and the other part in C/C++.
  • You can write the whole application in C/C++.

NOTE: NDK support was added in Android 1.5. Today very few devices run Android versions older than 1.5, and it is therefore safe to use the NDK to write part of your application in C/C++. However, writing your entire application in C/C++ requires Android 2.3 or later.

This chapter starts by showing you what the NDK is made of. Then, we will take a look at how to mix C/C++ code with Java code in an Android application, and how to make sure the code is optimized for all platforms you want to target. Finally, we'll delve into a new class, NativeActivity, introduced in Android 2.3 that allows you to write your whole application in C/C++, and we'll show you a simple example of using sensors in your C/C++ code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.116.69