Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
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
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Billing Address

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

Android Native Development Kit Cookbook

Chapter 2. Java Native Interface

In this chapter, we will cover the following recipes:

  • Loading native libraries and registering native methods

  • Passing parameters and receiving returns in primitive types

  • Manipulating strings in JNI

  • Managing references in JNI

  • Manipulating classes in JNI

  • Manipulating objects in JNI

  • Manipulating arrays in JNI

  • Accessing Java static and instance fields in native code

  • Calling static and instance methods from native code

  • Caching jfieldID, jmethodID, and reference data to improve performance

  • Checking errors and handling exceptions in JNI

  • Integrating assembly code in JNI

Introduction


Programming with Android NDK is essentially writing code in both Java and native languages such as C, C++, and assembly. Java code runs on Dalvik Virtual Machine (VM), while native code is compiled to binaries running directly on the operating system. Java Native Interface (JNI) acts like the bridge that brings both worlds together. This relationship between Java code, Dalvik VM, native code, and the Android system can be illustrated using the following diagram:

The arrow in the diagram indicates which party initiates the interaction. Both Dalvik VM and Native Code run on top of Android system (Android is a Linux-based OS). They require the system to provide the execution environment. JNI is part of Dalvik VM, which allows Native Code to access fields and invoke methods at Java Code. JNI also allows Java Code to invoke native methods implemented in Native Code. Therefore, JNI facilitates the two-way communication between Native Code and Java Code.

If you are familiar with Java...

Loading native libraries and registering native methods


Native code is usually compiled into a shared library and loaded before the native methods can be called. This recipe covers how to load native libraries and register native methods.

Getting ready

Please read the recipes in Chapter 1, Hello NDK, to set up the Android NDK development environment if you haven't done so already.

How to do it…

The following steps will show you how to build an Android application that demonstrates loading native libraries and registering native methods:

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

  2. In the next window, select the latest version of Android SDK, then click on Next to go to the next window.

  3. Specify the package name as cookbook.chapter2. Select the Create Activity checkbox, and specify the name as NativeMethodsRegisterActivity. Set the value for Minimum SDK as 5 (Android 2...

Passing parameters and receiving returns in primitive types


Java code can pass parameters to native methods and receive the processing results returned. This recipe walks through how to pass parameters and receive returns in primitive types.

Getting ready

You should have built at least one Android application with native code before reading this recipe. If you haven't done so, please read the Writing a Hello NDK program recipe in Chapter 1, Hello NDK first.

How to do it…

The following steps create a sample Android application with native methods receiving input parameters from the Java code and returning the processing result back:

  1. Create a project named PassingPrimitive. Set the package name as cookbook.chapter2. Create an activity named PassingPrimitiveActivity. Under this project, create a folder named jni. Please refer to the Loading native libraries and registering native methods recipe in this chapter if you want more detailed instructions.

  2. Add a file named primitive.c under the jni folder...

Manipulating strings in JNI


Strings are somewhat complicated in JNI, mainly because Java strings and C strings are internally different. This recipe will cover the most commonly used JNI string features.

Getting ready

Understanding the basics of encoding is essential to comprehend the differences between Java string and C string. We'll give a brief introduction to Unicode.

According to the Unicode Consortium, the Unicode Standard is defined as follows:

The Unicode Standard is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages and technical disciplines of the modern world. In addition, it supports classical and historical texts of many written languages.

Unicode assigns a unique number for each character it defines, called code point. There are mainly two categories of encoding methods that support the entire Unicode character set, or a subset of it.

The first one is the Unicode Transformation Format...

Managing references in JNI


JNI exposes strings, classes, instance objects, and arrays as reference types. The previous recipe introduces the string type. This recipe will cover reference management and the subsequent three recipes will discuss class, object, and arrays respectively.

How to do it…

The following steps create a sample Android project that illustrates reference management in JNI:

  1. Create a project named ManagingReference. Set the package name as cookbook.chapter2. Create an activity named ManagingReferenceActivity. Under the project, create a folder named jni. Refer to the Loading native libraries and registering native methods recipe in this chapter, if you want more detailed instructions.

  2. Create a file named referencetest.c under the jni folder, then implement the localReference, globalReference, weakReference, and referenceAssignmentAndNew methods. This is shown in the following code snippet:

    JNIEXPORT void JNICALL Java_cookbook_chapter2_ManagingReferenceActivity_localReference...

Manipulating classes in JNI


The previous recipe discusses that Android JNI supports three different kinds of references. The references are used to access the reference data types, including string, class, instance object, and array. This recipe focuses on class manipulations in Android JNI.

Getting ready

The Managing References in NDK recipe should be read first before going through this recipe.

How to do it…

The following steps describe how to build a sample Android application that illustrates class manipulation in JNI:

  1. Create a project named ClassManipulation. Set the package name as cookbook.chapter2. Create an activity named ClassManipulationActivity. Under the project, create a folder named jni. Refer to the Loading native libraries and registering native methods recipe of this chapter if you want more detailed instructions.

  2. Create a file named classtest.c under the jni folder, then implement the findClassDemo, findClassDemo2, GetSuperclassDemo, and IsAssignableFromDemo methods. We can...

Manipulating objects in JNI


The previous recipe shows how we can manipulate classes in Android JNI. This recipe describes how to manipulate instance objects in Android NDK programming.

Getting ready

The following recipes should be read first before going through this recipe:

  • Managing references in JNI

  • Manipulating classes in JNI

How to do it…

Now we'll create an Android project with native methods demonstrating the usage of JNI functions related to instance objects. Perform the following steps:

  1. Create a project named ObjectManipulation. Set the package name as cookbook.chapter2. Create an activity named ObjectManipulationActivity. Under the project, create a folder named jni. Please refer to the Loading native libraries and registering native methods recipe in this chapter, if you want more detailed instructions.

  2. Create a file named objecttest.c under the jni folder, then implement the AllocObjectDemo, NewObjectDemo, NewObjectADemo, NewObjectVDemo, GetObjectClassDemo, and IsInstanceOfDemo methods...

Manipulating arrays in JNI


JNI exposes strings, classes, instance objects, and arrays as reference types. This recipe will discuss arrays in JNI.

Getting ready

You should make sure you've read the following recipes before going through this recipe:

  • Managing references in JNI

  • Manipulating classes in JNI

How to do it…

In this section, we will create a sample Android project that demonstrates how to manipulate arrays in JNI.

  1. Create a project named ArrayManipulation. Set the package name as cookbook.chapter2. Create an activity named ArrayManipulationActivity. Under the project, create a folder named jni. Refer to the Loading native libraries and registering native methods recipe of this chapter for more detailed instructions.

  2. Create a file named arraytest.c under the jni folder, then implement the GetArrayLengthDemo, NewObjectArrayDemo, NewIntArrayDemo, GetSetObjectArrayDemo, GetReleaseIntArrayDemo, GetSetIntArrayRegionDemo, and GetReleasePrimitiveArrayCriticalDemo native methods.

  3. Modify ArrayManipulationActivity...

Accessing Java static and instance fields in the native code


We have demonstrated how to pass parameters of different types to native methods and return data back to Java. This is not the only way of sharing data between the native code and Java code. This recipe covers another method—accessing Java fields from the native code.

Getting ready

We're going to cover how to access Java fields of different types, including primitive types, strings, instance objects, and arrays. The following recipes should be read first before reading this recipe:

  • Passing parameters and receiving returns in primitive types

  • Manipulating strings in JNI

  • Manipulating classes in JNI

  • Manipulating objects in JNI

  • Manipulating arrays in JNI

Readers are also expected to be familiar with Java reflection API.

How to do it…

Follow these steps to create a sample Android project that demonstrates how to access Java static and instance fields from the native code:

  1. Create a project named AccessingFields. Set the package name as cookbook...

Calling static and instance methods from the native code


The previous recipe covers how to access Java fields in NDK. Besides fields, a Java class also has methods. This recipe focuses on calling static and instance methods from JNI.

Getting ready

The code examples require a basic understanding of the JNI primitive types, strings, classes, and instance objects. It is better to make sure you have read the following recipes before going through this recipe:

  • Passing parameters and receiving returns in primitive types

  • Manipulating strings in JNI

  • Manipulating classes in JNI

  • Manipulating objects in JNI

  • Accessing Java static and instance fields in native code

Readers are also expected to be familiar with Java reflection API.

How to do it…

The following steps can be followed to create a sample Android project that illustrates how to call static and instance methods from the native code:

  1. Create a project named CallingMethods. Set the package name as cookbook.chapter2. Create an activity named CallingMethodsActivity...

Caching jfieldID, jmethodID, and referencing data to improve performance


This recipe covers caching in Android JNI, which can improve the performance of our native code.

Getting ready

You should make sure you've read the following recipes before going through this recipe:

  • Accessing Java static and instance fields in native code

  • Calling static and instance methods from native code

How to do it…

The following steps detail how to build a sample Android application that demonstrates caching in JNI:

  1. Create a project named Caching. Set the package name as cookbook.chapter2. Create an activity named CachingActivity. Under the project, create a folder named jni. Refer to the Loading native libraries and registering native methods recipe of this chapter for more detailed instructions.

  2. Create a file named cachingtest.c under the jni folder, then implement the InitIDs, CachingFieldMethodIDDemo1, CachingFieldMethodIDDemo2, and CachingReferencesDemo methods.

  3. Modify the CachingActivity.java file by adding code...

Checking errors and handling exceptions in JNI


JNI functions can fail because of system constraint (for example, lack of memory) or invalid arguments (for example, passing a native UTF-8 string when the function is expecting a UTF-16 string). This recipe discusses how to handle errors and exceptions in JNI programming.

Getting ready

The following recipes should be read first before proceeding with this recipe:

  • Manipulating strings in JNI

  • Managing references in JNI

  • Accessing Java static and instance fields in native code

  • Calling static and instance methods from native code

How to do it…

Follow these steps to create a sample Android project that illustrates errors and exception handling in JNI:

  1. Create a project named ExceptionHandling. Set the package name as cookbook.chapter2. Create an activity named ExceptionHandlingActivity. Under the project, create a folder named jni. Refer to the Loading native libraries and registering native methods recipe of this chapter for more detailed instructions...

Integrating assembly code in JNI


Android NDK allows you to write assembly code at JNI programming. Assembly code is sometimes used to optimize the critical portion of code to achieve the best performance. This recipe does not intend to discuss how to program in assembly. It describes how to integrate assembly code in JNI programming instead.

Getting ready

Read the Passing parameters and receiving returns in primitive types recipe before you continue.

How to do it…

The following steps create a sample Android project that integrates the assembly code:

  1. Create a project named AssemblyInJNI. Set the package name as cookbook.chapter2. Create an activity named AssemblyInJNIActivity. Under the project, create a folder named jni. Refer to the Loading native libraries and registering native methods recipe of this chapter for more detailed instructions.

  2. Create a file named assemblyinjni.c under the jni folder, then implement the InlineAssemblyAddDemo method.

  3. Create a file named tmp.c under the jni folder...

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
  •  

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 : 9781849691512
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 116.97
Android Native Development Kit Cookbook
€41.99
Asynchronous Android
€32.99
Android NDK Game Development Cookbook
€41.99
Total 116.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.