Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Android Native Development Kit Cookbook
Android Native Development Kit Cookbook

Android Native Development Kit Cookbook: Create Android apps using Native C/C++ with the expert guidance contained in this cookbook. From basic routines to advanced multimedia development, it helps you harness the full power of Android NDK.

eBook
$9.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Android Native Development Kit Cookbook

Chapter 1. Hello NDK

In this chapter, we will cover the following recipes:

  • Setting up an Android NDK development environment in Windows

  • Setting up an Android NDK development environment in Ubuntu Linux

  • Setting up an Android NDK development environment in Mac OS

  • Updating Android NDK

  • Writing a Hello NDK program

Introduction


Android NDK is a toolset that allows developers to implement a part of or an entire Android application in a native language, such as C, C++, and assembly. Before we start our journey to NDK, it is important to understand the advantages of NDK.

First of all, NDK may improve application performance. This is usually true for many processor-bound applications. Many multimedia applications and video games use native code for processor-intensive tasks.

The performance improvements can come from three sources. Firstly, the native code is compiled to a binary code and run directly on OS, while Java code is translated into Java byte-code and interpreted by Dalvik Virtual Machine (VM). At Android 2.2 or higher, a Just-In-Time (JIT) compiler is added to Dalvik VM to analyze and optimize the Java byte-code while the program is running (for example, JIT can compile a part of the byte-code to binary code before its execution). But in many cases, native code still runs faster than Java code.

Tip

Java code is run by Dalvik VM on Android. Dalvik VM is specially designed for systems with constrained hardware resources (memory space, processor speed, and so on).

The second source for performance improvements at NDK is that native code allows developers to make use of some processor features that are not accessible at Android SDK, such as NEON, a Single Instruction Multiple Data (SIMD) technology, allowing multiple data elements to be processed in parallel. One particular coding task example is the color conversion for a video frame or a photo. Suppose we are to convert a photo of 1920x1280 pixels from the RGB color space to the YCbCr color space. The naive approach is to apply a conversion formula to every pixel (that is, over two million pixels). With NEON, we can process multiple pixels at one time to reduce the processing time.

The third aspect is that we can optimize the critical code at an assembly level, which is a common practice in desktop software development.

Tip

The advantages of using native code do not come free. Calling JNI methods introduces extra work for the Dalvik VM and since the code is compiled, no runtime optimization can be applied. In fact, developing in NDK doesn't guarantee a performance improvement and can actually harm performance at times. Therefore, we only stated that it may improve the app's performance.

The second advantage of NDK is that it allows the porting of existing C and C++ code to Android. This does not only speed up the development significantly, but also allows us to share code between Android and non-Android projects.

Before we decide to use NDK for an Android app, it is good to know that NDK will not benefit most Android apps. It is not recommended to work in NDK simply because one prefers programming in C or C++ over Java. NDK cannot access lots of APIs available in the Android SDK directly, and developing in NDK will always introduce extra complexity into your application.

With the understanding of the pros and cons of NDK, we can start our journey to Android NDK. This chapter will cover how to set up Android NDK development in Windows, Ubuntu Linux, and Mac OS. For developers who have set up an Android NDK development environment before, a recipe with detailed steps of how to update an NDK development environment is provided. At the end of the chapter, we will write a Hello NDK program with the environment setup.

Setting up an Android NDK development environment in Windows


In this recipe, we will explore how to set up an Android NDK development environment in Windows.

Getting ready

Check the Windows edition and system type. An Android development environment can be set up on Windows XP 32-bit, Windows Vista 32- or 64-bit, and Windows 7 32- or 64-bit.

Android development requires Java JDK 6 or above to be installed. Follow these steps to install and configure Java JDK:

  1. Go to the Oracle Java JDK web page at http://www.oracle.com/technetwork/java/javase/downloads/index.html, and choose JDK6 or above for your platform to download.

  2. Double-click on the downloaded executable, and click through the installation wizard to finish the installation.

  3. Go to Control Panel | System and Security | System | Advanced system settings. A System Properties window will pop up.

  4. Click on the Environment Variables button in the Advanced tab; another Environment Variables window will pop up.

  5. Under System variables, click on New to add a variable with the name as JAVA_HOME and value as the path of the JDK installation root directory. This is shown as follows:

  6. Under System variables, scroll to find the PATH (or Path) environment variable. Insert %JAVA_HOME%\bin; at the beginning of the value. If no PATH or Path variable exists, create a new variable with the value set to %JAVA_HOME%\bin. Click on OK all the way through to dismiss all windows.

  7. To verify whether JDK is installed and configured correctly, start a new command-line console, and enter javac -version. If JDK is configured correctly, you will get the Java version in the output.

Cygwin is a Linux-like environment for Windows to run software available on Linux. Android NDK development requires Cygwin 1.7 or higher installed to execute some Linux programs; for example, the GNU make.

Since NDK r7, the Windows NDK comes with a new ndk-build.cmd build script, which uses NDK's prebuilt binaries for GNU make, awk, and other tools. Therefore Cygwin is not required for building NDK programs with ndk-build.cmd. However, it is recommended that you still install Cygwin, because ndk-build.cmd is an experimental feature and Cygwin is still needed by the debugging script ndk-gdb.

Follow these steps to install Cygwin:

  1. Go to http://cygwin.com/install.html to download setup.exe for Cygwin. Double-click on it after the download is complete in order to start the installation.

  2. Click on Next, then select Install from Internet. Keep clicking on Next until you see the Available Download Sites list. Select the site that is close to your location, then click on Next:

  3. Look for GNU make under Devel, ensure it is version 3.81 or later, and gawk under Base. Alternatively, you can search for make and gawk using the Search box. Make sure both GNU make and gawk are selected to install, then click on Next. The installation can take a while to finish:

Eclipse is a powerful software Integrated Development Environment (IDE) with an extensible plugin system. It is the recommended IDE to develop Android apps. Go to http://www.eclipse.org/downloads/, and download the Eclipse Classic or Eclipse IDE for Java developers. Extract the compressed file and it will be ready for use. Note that Android development requires Eclipse 3.6.2 (Helios) or greater.

Tip

The Android developer website provides an Android Developer Tools bundle at http://developer.android.com/sdk/index.html. It includes the Eclipse IDE with the ADT plugin, and the Android SDK. We can download this bundle and skip the SDK installation described in steps 1 to 10 of the following How to do it... section.

How to do it…

The following steps show you how to set up an Android NDK development environment in Windows. We will first set up an SDK development environment. Steps 1 to 10 can be skipped if SDK is already set up.

  1. Start Eclipse. Select Help | Install New Software, and a window titled Install will pop up.

  2. Click on the Add… button at the top-right will corner, and another window titled Add Repository will pop up.

  3. In the Add Repository window, enter ADT for Name and https://dl-ssl.google.com/android/eclipse/ for Location. Then click on OK.

  4. It may take a few seconds for Eclipse to load the software items from the ADT website. After loading, select Developer Tools and NDK Plugins, then click on Next to proceed:

  5. In the next window, a list of tools to be installed will be shown. Simply click on Next. Read and accept all the license agreements, then click on Finish.

  6. After installation finishes, restart Eclipse as prompted.

  7. Download Android SDK from http://developer.android.com/sdk/index.html.

  8. Double-click on the installer to start the installation. Follow the wizard to finish the installation.

  9. In Eclipse, select Window | Preferences to open the Preferences window. Select Android from the left panel, then click on Browse to locate the Android SDK root directory. Click on Apply, and then OK.

  10. Start Android SDK Manager at the Android SDK installation root directory. Select Android SDK Tools, Android SDK Platform-tools, at least one Android platform (the latest is preferred), System Image, SDK Samples, and Android Support. Then click on Install. in the next window, read and accept all the license agreements, then click on Install:

  11. Go to http://developer.android.com/tools/sdk/ndk/index.html to download the latest version of Android NDK. Unzip the downloaded file.

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  12. Open Cygwin.bat under the cygwin root directory. It contains the following content by default:

    @echo off
    C:
    chdir C:\cygwin\bin
    bash --login -i
  13. Add the following content after @echo off before C:

    set IS_UNIX=
    set JAVA_HOME=<JDK path>
    set PATH=<SDK path>\tools;<NDK path>
    set ANDROID_NDK_ROOT=/cygdrive/<NDK path>

    As an example, the file content on my machine is as follows; note that Progra~1 is the short name for the Program Files folder:

    set IS_UNIX=set JAVA_HOME=c:/Progra~1/Java/jdk1.7.0_05
    set PATH=C:/Users/Administrator/AppData/Local/Android/android-sdk/tools;C:/Users/Administrator/Downloads/android-ndk-r8-windows/android-ndk-r8
    set ANDROID_NDK_ROOT=/cygdrive/c/Users/Administrator/Downloads/android-ndk-r8-windows/android-ndk-r8
  14. Start Cygwin by double-clicking on cygwin.bat, then go to the samples/hello-jni directory in NDK. Type the command ndk-build. If the build is successful, it proves that the NDK environment is set up correctly:

  15. In Eclipse, select Window | Preferences to open the Preferences window. Click on Android from the left panel, and select NDK from the drop-down list. Click on Browse to locate the Android NDK root directory. Click on OK to dismiss the pop-up window. This enables us to build and debug Android NDK applications with the Eclipse NDK plugin:

How it works…

In this recipe, we first set up an Android SDK development environment and then the NDK development environment.

Android NDK does not require installation. We downloaded NDK, and configured the path to make it more convenient to use.

Cygwin is not required for Android SDK development, but is essential for NDK development because NDK uses some Linux tools that depend on Cygwin.

NDK plugin in ADT: NDK plugin for Eclipse is available in Android Development Tools (ADT), which allows us to build and debug Android NDK applications easily.

Tip

The NDK plugin is only available for ADT 20.0.0 or later, which was released on June 2012. You may want to update your Eclipse ADT in order to use the NDK plugin.

There's more…

We installed Eclipse IDE as a part of our development environment. Eclipse is the recommended IDE for developing Android applications, and it comes with lots of useful tools and utilities to help our development. However, it is not a compulsory component of the development environment.

Setting up an Android NDK development environment in Ubuntu Linux


This recipe depicts how to set up an Android NDK development environment in Ubuntu Linux.

Getting ready

Check your Ubuntu version and make sure it is version 8.04 or later.

GNU C Library (glibc) 2.7 or above is required. It is usually installed with Linux by default. Two simple methods can check the version of glibc:

  1. Start a terminal, and enter ldd --version. This will print the version of ldd and glibc:

  2. We can execute the library as an application. Start a terminal, locate the library location, and then enter the following command:

    <glibc library location>/<glibc library>. 
    

    The following output will be displayed:

  3. We need to enable 32-bit application execution if we are using a 64-bit machine. Start a terminal, and enter the following command:

    sudo apt-get install ia32-libs
    
  4. Install JDK 6 or above. At a terminal, enter the command sudo apt-get install openjdk-6-jdk, or alternatively we can enter sudo apt-get install sun-java6-jdk. After installation, we need to add the JDK path to the PATH environment variable by adding the following lines to ~/.bashrc:

    export JDK_PATH=/usr/local/jdk1.7.0/bin
    export PATH=$PATH:$JDK_PATH

We will use Eclipse as our IDE. Please refer to the Setting up an Android NDK development environment in Windows recipe for instructions.

How to do it…

The following steps indicate the procedure of setting up an Android NDK development environment on Ubuntu Linux:

  1. Follow steps 1 to 6 of the Setting up an Android NDK development environment in Windows recipe to install the ADT plugin for Eclipse.

  2. Download Android SDK from http://developer.android.com/sdk/index.html, then extract the downloaded package.

  3. Append the following lines to ~/.bashrc:

    export ANDROID_SDK=<path to Android SDK directory>
    export PATH=$PATH:$ ANDROID_SDK/tools:$ANDROID_SDK/platform-tools
  4. Follow steps 9 and 10 of the Setting up an Android NDK development environment in Windows recipe to configure the SDK path at Eclipse, and download additional packages.

  5. Download the latest version of Android NDK from http://developer.android.com/tools/sdk/ndk/index.html, then extract the downloaded file.

  6. Change the lines that you appended to ~/.bashrc in step 3:

    export ANDROID_SDK=<path to Android SDK directory>
    export ANDROID_NDK=<path to Android NDK directory> 
    export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools:$ANDROID_NDK
  7. Start a new terminal, then go to the samples/hello-jni directory in NDK. Type the command ndk-build. If the build is successful, it proves that the NDK environment is set up correctly:

How it works…

We first set up Android SDK and then Android NDK. Ensure that the path is set properly, so that the tools can be accessed without referring to the SDK and NDK directories.

The .bashrc file is a startup file read by the bash shell when you start a new terminal. The export commands appended the Android SDK and NDK directory locations to the environment variable PATH. Therefore, every time a new bash shell starts, PATH is set properly for SDK and NDK tools.

There's more…

The following are a few more tips on setting up an NDK development environment:

  • Configure Path at Startup File: We append to the SDK and NDK paths to the PATH environment variable at ~/.bashrc file. This assumes that our Linux system uses the bash shell. However, if your system uses another shell, the startup file used may be different. The startup files used by some commonly used shells are listed as follows:

    • For C shell (csh), the startup file to use is ~/.cshrc.

    • For ksh, the startup file to use can be obtained using the command echo $ENV.

    • For sh, the startup file to use is ~/.profile. The user needs to log out of the current session and log in again for it to take effect.

  • Switch JDK: In Android development, we can either use Oracle Java JDK or OpenJDK. In case we run into issues with any one of the JDKs, we can switch to another Java JDK, if we have installed both of them.

    • To check which JDK the system is currently using, use the following command:

      	$update-java-alternatives -l
      
    • To switch between two JDKs, use the following command:

      	$sudo update-java-alternatives -s <java name>
      

    The following is an example for switching to Oracle JDK 1.6.0:

    $sudo update-java-alternatives -s java-1.6.0-sun 
    

Setting up an Android NDK development environment in Mac OS


This recipe describes how to set up an Android NDK development environment in Mac OS.

Getting ready

Android development requires Mac OS X 10.5.8 or higher, and it works on the x86 architecture only. Ensure that your machine meets these requirements before getting started.

Register an Apple developer account, then go to https://developer.apple.com/xcode/ to download Xcode, which contains a lot of developer tools, including the make utility required for Android NDK development. After the download is complete, run the installation package and make sure that the UNIX Development option is selected for installation.

As usual, Java JDK 6 or above is required. Mac OS X usually ships with a full JDK. We can verify that your machine has the required version by using the following command:

$javac -version

How to do it…

Setting up an Android NDK development environment on Mac OS X is similar to setting it up on Ubuntu Linux. The following steps explain how we can do this:

  1. Follow steps 1 to 6 of the Setting up an Android NDK development environment in Windows recipe to install the ADT plugin for Eclipse.

  2. Download Android SDK from http://developer.android.com/sdk/index.html, then extract the downloaded package.

  3. Append the following lines to ~/.profile. If the file doesn't exist, create a new one. Save the changes and log out of the current session:

    export ANDROID_SDK=<path to Android SDK directory>
    export PATH=$PATH:$ ANDROID_SDK/tools:$ANDROID_SDK/platform-tools
  4. In Eclipse, select Eclipse | Preferences to open the Preferences window. Select Android from the left panel, then click on Browse to locate the Android SDK root directory. Click on Apply, and then OK.

  5. In a terminal, start the Android SDK Manager at the tools directory by typing the command android. Select Android SDK Tools, Android SDK Platform-tools, at least one Android platform (the latest one is preferred), System Image, SDK Samples, and Android Support. Then click on Install. In the next window, read and accept all the license agreements, then click on Install.

  6. Download Android SDK from http://developer.android.com/sdk/index.html, and then extract the downloaded package.

  7. Change the lines that you appended to ~/.profile in step 3:

    export ANDROID_SDK=<path to Android SDK directory>
    export ANDROID_NDK=<path to Android NDK directory> 
    export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools:$ANDROID_NDK
  8. Start a new terminal, then go to the samples/hello-jni directory in NDK. Type the command ndk-build. If the build is successful, it proves that the NDK environment is set up correctly.

How it works…

The steps to set up an Android NDK development environment on Mac OS X are similar to Ubuntu Linux, since both of them are Unix-like operating systems. We first installed Android SDK, then Android NDK.

Updating Android NDK


When there is a new release of NDK, we may want to update NDK in order to take advantage of the new features or bug fixes with the new release. This recipe talks about how to update Android NDK in Windows, Ubuntu Linux, and Mac OS.

Getting ready

Please read the previous recipes in this chapter, depending on the platform of your choice.

How to do it…

In Windows, follow these instructions to update Android NDK:

  1. Go to http://developer.android.com/tools/sdk/ndk/index.html to download the latest version of Android NDK. Unzip the downloaded file.

  2. Open Cygwin.bat under the cygwin root directory. The content should be similar to the following code snippet, if you have previously configured NDK on the system:

    @echo off
    set IS_UNIX=
    set JAVA_HOME=<JDK path>
    set PATH=<SDK path>\tools;<NDK path>
    set ANDROID_NDK_ROOT=/cygdrive/<NDK path>
    C:
    chdir C:\cygwin\bin
    bash --login -i
  3. Update <NDK path> from the old NDK path to the newly downloaded and decompressed location.

In Ubuntu Linux, follow these instructions to update Android NDK:

  1. Download the latest version of Android NDK from http://developer.android.com/tools/sdk/ndk/index.html, then extract the downloaded file.

  2. If we have followed the Setting up an Android NDK development environment in Ubuntu Linux recipe, the following content should appear at the end of ~/.bashrc:

    export ANDROID_SDK=<path to Android SDK directory>
    export ANDROID_NDK=<path to Android NDK directory>
    export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools:$ANDROID_NDK
  3. Update the ANDROID_NDK path to the newly downloaded and extracted Android NDK folder.

In Mac OS, the steps are almost identical to Ubuntu Linux, except that we need to append the path to ~/.profile instead of ~/.bashrc.

How it works…

NDK installation is completed by simply downloading and extracting the NDK file, and configuring the path properly. Therefore, updating NDK is as simple as updating the configured path to the new NDK folder.

There's more…

Sometimes, updating NDK requires updating SDK first. Since this book focuses on Android NDK, explaining how to update SDK is beyond the scope of this book. You can refer to the Android developer website at http://developer.android.com/sdk/index.html, for details on how to do it.

At times, we may feel the need to use an old version of NDK to build certain applications because of compatibility issues. Therefore, it may be useful to keep multiple versions of Android NDK and switch between them by changing the path or simply using the full path to refer to a specific version of NDK.

Writing a Hello NDK program


With the environment set up, let's start writing the code in NDK. This recipe walks through a Hello NDK program.

Getting ready

The NDK development environment needs to be set up properly before starting to write the Hello NDK program. Please refer to previous recipes in this chapter, depending upon the platform of your choice.

How to do it…

Follow these steps to write, compile, and run the Hello NDK program:

  1. Start Eclipse, and select File | New | Android Project. Enter HelloNDK as the value for Project Name. Select Create new project in workspace. Then click on Next:

  2. In the next window, select an Android version that you want to target. Usually, the latest version is recommended. Then click on Next.

  3. In the next window, specify your package name as cookbook.chapter1. Select the Create Activity box, and specify the name as HelloNDKActivity. Set the value for Minimum SDK as 5 (Android 2.0). Click on Finish:

  4. In the Eclipse package explorer, right-click on the HelloNDK project, and select New | Folder. Enter the name jni in the pop-up window, then click on Finish:

  5. Right-click on the newly-created jni folder under the HelloNDK project. Select New | File, enter hello.c as the value for File name, then click on Finish. Type the following code in the hello.c file:

    #include <string.h>
    #include <jni.h>
    
    jstring 
    Java_cookbook_chapter1_HelloNDKActivity_naGetHelloNDKStr(JNIEnv* pEnv,  jobject pObj)
    {
        return (*pEnv)->NewStringUTF(pEnv, "Hello NDK!");
    }
  6. Right-click on the jni folder. Select New | File, enter Android.mk as the value for File name, then click on Finish. Type the following code in the Android.mk file:

    LOCAL_PATH := $(call my-dir)
    include $(CLEAR_VARS)
    LOCAL_MODULE    := hello
    LOCAL_SRC_FILES := hello.c
    include $(BUILD_SHARED_LIBRARY)
  7. Start a terminal, go to the jni folder, and type ndk-build to build the hello.c program as a native library.

  8. Edit the HelloNDKActivity.java file. The file should contain the following content:

    public class HelloNDKActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            TextView tv = new TextView(this);
            tv.setTextSize(30);
            tv.setText(naGetHelloNDKStr());
            this.setContentView(tv);
        }
        public native String naGetHelloNDKStr();
        static {
            System.loadLibrary("hello");
        }
    }
  9. Right-click on the HelloNDK project in Eclipse. Select Run As | Android Application. Your Android phone or emulator will be displayed with something similar to the following screenshot:

How it works…

This recipe demonstrated how to write a Hello NDK program on Android.

  • Native code: The Hello NDK program consists of both the native C code and Java code. The native function naGetHelloNDKStr returns the Hello NDK string to the caller, as indicated in both the native code function definition and Java code method declaration. The native function name must follow a specific pattern for a package name, class name, and method name. The package and class name must agree with the package and class name of the Java class from which the native method is called, while the method name must be the same as the method name declared in that Java class.

    This helps the Dalvik VM to locate the native function at runtime. Failing to follow the rule will result in UnsatisfiedLinkError at runtime.

    The native function has two parameters, which are standard for all native functions. Additional parameters can be defined based on needs. The first parameter is a pointer to JNIEnv , which is the gateway to access various JNI functions. The meaning of the second parameter depends on whether the native method is a static or an instance method. If it's a static method, the second parameter is a reference to the class where the method is defined. If it's an instance method, the second parameter is a reference to the object on which the native method is invoked. We will discuss JNI in detail in Chapter 2, Java Native Interface.

  • Compilation of the native code: The Android NDK build system frees developers from writing makefile. The build system accepts an Android.mk file, which simply describes the sources. It will parse the file to generate makefile and do all the heavy lifting for us.

    We will cover details of how to write the Android.mk file or even write our own makefile in Chapter 3, Build and Debug NDK Applications.

    Once we compile the native code, a folder named libs will be created under our project and a libhello.so library will be generated under the armeabi subdirectory.

  • Java code: Three steps are followed to call the native method:

    1. Load the native library: This is done by calling System.loadLibrary("hello"). Note that instead of libhello, we should use hello. The Dalvik VM will fail to locate the library if libhello is specified.

    2. Declare the method: We declare the method with a native keyword to indicate that it is a native method.

    3. Invoke the method: We call the method just like any normal Java method.

There's more…

The name of a native method is lengthy and writing it manually is error-prone. Fortunately, the javah program from JDK can help us generate the header file, which includes the method name. The following steps should be followed to use javah:

  1. Write the Java code, including the native method definition.

  2. Compile the Java code and make sure the class file appears under the bin/classes/ folder of our project.

  3. Start a terminal and go to the jni folder, and enter the following command:

    $ javah -classpath ../bin/classes –o <output file name> <java package name>.<java class anme>
    

    In our HelloNDK example, the command should be as follows:

    $ javah -classpath ../bin/classes –o hello.h cookbook.chapter1.HelloNDKActivity
    

    This will generate a file named hello.h with its function definition as follows:

    JNIEXPORT jstring JNICALL Java_cookbook_chapter1_HelloNDKActivity_naGetHelloNDKStr
      (JNIEnv *, jobject);
Left arrow icon Right arrow icon

Key benefits

  • Build, debug, and profile Android NDK apps
  • Implement part of Android apps in native C/C++ code
  • Optimize code performance in assembly with Android NDK

Description

Building Android applications would usually mean that you spend all of your time working in Java. There are however times when this is not the most efficient or best method for the application being built. This is where Android NDK comes in. Android NDK allows the developer to write in Native C/C++, giving you the power to reuse code and libraries and also, in most cases, increase the speed and efficiency of your application.The "Android Native Development Kit Cookbook" will help you understand the development, building, and debugging of your native Android applications. We will discover and learn JNI programming and essential NDK APIs such as OpenGL ES, and the native application API. We will then explore the process of porting existing libraries and software to NDK. By the end of this book you will be able to build your own apps in NDK apps."Android Native Development Kit Cookbook" begins with basic recipes that will help you in the building and debugging of native apps, and JNI programming. The recipes cover various topics of application development with Android NDK such as OpenGL programming and Multimedia programming. We will begin with a simple recipe, Hello NDK, before moving on to cover advanced topics with recipes on OpenGL ES that focus on 2D and 3D graphics, as well as recipes that discuss working with NDK and external APIs. If you are looking for ways to make your application available in Android and take measures to boost your application's performance, then this Cookbook is for you.

Who is this book for?

Android developers who want to learn Android NDK programming, or develop multimedia and games in Android NDK will benefit from this book.

What you will learn

  • Develop Android apps in C/C++ without a single line of Java
  • Program 2D/3D graphics with both OpenGL ES 1x and 2.0 in Android NDK
  • Write multi-threaded Android apps in Android NDK
  • Port existing C/C++ libraries and applications to Android with NDK
  • Develop multimedia Android apps with Android NDK
  •  
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 26, 2013
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691505
Category :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to South Korea

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Mar 26, 2013
Length: 346 pages
Edition : 1st
Language : English
ISBN-13 : 9781849691505
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 153.97
Android Native Development Kit Cookbook
$54.99
Asynchronous Android
$43.99
Android NDK Game Development Cookbook
$54.99
Total $ 153.97 Stars icon
Banner background image

Table of Contents

9 Chapters
Hello NDK Chevron down icon Chevron up icon
Java Native Interface Chevron down icon Chevron up icon
Build and Debug NDK Applications Chevron down icon Chevron up icon
Android NDK OpenGL ES API Chevron down icon Chevron up icon
Android Native Application API Chevron down icon Chevron up icon
Android NDK Multithreading Chevron down icon Chevron up icon
Other Android NDK API Chevron down icon Chevron up icon
Porting and Using the Existing Libraries with Android NDK Chevron down icon Chevron up icon
Porting an Existing Application to Android with NDK Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(12 Ratings)
5 star 16.7%
4 star 66.7%
3 star 0%
2 star 0%
1 star 16.7%
Filter icon Filter
Top Reviews

Filter reviews by




povilas Jun 09, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book can be very useful for Android developers who doesn't have much experience in native C++ development. The book describes in details the process of NDK setup and building applications with NDK. It also gives entry level introduction into JNI with some very useful tips and tricks. Information is well structured and organized in cookbook recipe style. It not only shows code samples but also provides understandable explanation how this code works and why it is necessary.I would definitely recommend this book.
Amazon Verified review Amazon
Fabio Radin May 23, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book gives a very detailed and exhaustive description of entry-level, intermediate and advanced techniques that could be used with Android NDK. All chapters, that are more or less independent of each other, explore specific arguments of Android JNI and NDK aspects. For the first time I saw in an Android NDK book the description of OpenGL (2D and 3D) and OpenMAX technologies from a native point of view. This allow you to write Android applications with a very limited number of Java code lines!In addition to that, the author describes a typical not documented approach in several other Android NDK books: the porting of an existing application to Android with NDK. This is a very useful chapter for people that could want to reuse existing libraries and applications written in C/C++ inside an Android one.I have to say that this book is not for everyone. You need to be a good C/C++ programmer because there are several required knowledges that must be well known by the reader (multithreading, semaphores, mutex, OpenGL, exceptions, OpenMAX, and so on), but, if you are curious about Android NDK and native code for Android, there are surely some chapters (in my opinion only a few) that could be for a large audience.In summary, I find the book perfect to make you a skilled Android NDK programmer! In addition, the two bonus chapters (available for download from website) are fantastic (I started reading the bonus chapters instead of the book!). If you love C/C++ language and in the same time you want to build applications for your Android device, this book is for you.Note: This book was provided for review by Packt.
Amazon Verified review Amazon
Sol_HSA Jun 19, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Although the name contains the word "cookbook", which to me says the book contains lots of small snippets, this book is actually a pretty much well-rounded tutorial on how to use the NDK. It starts off with setting up NDK on Windows, Linux and OSX, as well as a walkthrough of a hello world project.The book doesn't tiptoe around the fact that you really can't make a purely native application on Android; even if you use the "native activity", the java virtual machine is still there, behind the curtain. So it's a good thing the book covers the communication between the VM and native code in detail. There is also a chapter that covers the "native activity" approach as well, where you don't necessarily need to worry about the java side.. as much.Personally, I've only used printf debugging and Eclipse for NDK applications, so it was nice to find a chapter that covers different ways to build applications as well as different options for debuggers.Plenty of pages are devoted to threading, which I found a bit odd. The book also touches on a bunch of APIs one might want to use from NDK, like zlib, OpenSL ES, OpenMAX AL and OpenGL ES. While the intro to OpenGL ES may be helpful to some, there are complete books about this subject that are better sources for that information.Finally, there's a couple of chapters covering porting existing C code (libraries and applications) to Android and NDK. These are mostly step-by-step explanations of how to port some specific examples, where I would have preferred to see more of a list of things to keep in mind, pitfalls, what works, what doesn't, that sort of thing.If you're a desktop application developer and want to get your stuff running on your Android phone, and only want to buy one book, the topics of this book pretty much cover everything that you need to know.
Amazon Verified review Amazon
Rick Boyer May 26, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
When I saw preview copies of this book being offered, I jumped at the chance! As an experienced Android SDK developer with a background as a professional C/C++ developer, this is a topic I want to learn more about. I've only just opened the book, so these are my initial thoughts and I will post an update when I complete the book.The book starts with an introduction to the NDK and walks the user through setting up the environment. Even though I've already worked with the NDK, I still found good information in the first chapter. Remember, the NDK isn't for everything and the author explains the pros and cons of NDK development. There are not many chapters in the book, as this gives the author plenty of opportunity to go in depth on the topics. If the first chapter is representative of the rest of the book, this is going to be time well spent.
Amazon Verified review Amazon
Michael Sprayberry Jun 02, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book is a great start to learning Native Development for Android, it goes over a lot of the basic issues that a new programmer may happen into. This book is not a learners book for NDK but is a companion book for those learning NDK for Android. The chapters are well lined out and the author pulls from a lot of different sources to fill the cookbook with recipes to further develop your code and understanding of how the NDK can transform your applications. I would definitely recommend this for anyone programming Android and using the NDK to further their applications.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela