www.traintelco.com Android NDK Beginner's Guide Discover the nave side of Android and inject the power of C/C++ in your applicaons Sylvain Ratabouil BIRMINGHAM - MUMBAI www.traintelco.com Android NDK Beginner's Guide Copyright © 2012 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmied in any form or by any means, without the prior wrien permission of the publisher, except in the case of brief quotaons embedded in crical arcles or reviews. Every eort has been made in the preparaon of this book to ensure the accuracy of the informaon presented. However, the informaon contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark informaon about all of the companies and products menoned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this informaon. First published: January 2012 Producon Reference: 1200112 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-152-9 www.packtpub.com Cover Image by Marcus Grandon (marcusgrandon@mac.com) www.traintelco.com Credits Author Sylvain Ratabouil Reviewers Marko Gargenta Dr. Frank Grützmacher Robert Mitchell Acquision Editor Sarah Cullington Lead Technical Editor Dayan Hyames Technical Editor Pramila Balan Copy Editor Laxmi Subramanian Project Coordinator Jovita Pinto Proofreader Lynda Sliwoski Indexer Hemangini Bari Graphics Valenna D'silva Producon Coordinators Prachali Bhiwandkar Melwyn D'sa Nilesh Mohite Cover Work Alwin Roy www.traintelco.com About the Author Sylvain Ratabouil is a conrmed IT consultant with experience in C++ and Java technologies. He worked for the space industry and got involved in aeronauc projects at Valtech Technologies where he now takes part in the Digital Revoluon. Sylvain earned the master's degree in IT from Paul Sabaer University in Toulouse and did M.Sc. in Computer Science from Liverpool University. As a technology lover, he is passionate about mobile technologies and cannot live or sleep without his Android smartphone. I would like to thank Steven Wilding for oering me to write this book; Sneha Harkut and Jovita Pinto for awaing me with so much paence; Reshma Sundaresan, and Dayan Hyames for pung this book on the right track; Sarah Cullington for helping me nalizing this book; Dr. Frank Grützmacher, Marko Gargenta, and Robert Mitchell for all their helpful comments. www.traintelco.com About the Reviewers Dr. Frank Grützmacher has worked for several major German rms in the area of large distributed systems. He was an early user of dierent Corba implementaons in the past. He got his Ph.D. in the eld of electrical engineering, but with the focus on distributed heterogeneous systems. In 2010, he was involved in a project, which changed parts of the Android plaorm for a manufacturer. From there, he got his knowledge about the android NDK and nave processes on this plaorm. He has already worked as a reviewer for another Android 3.0 book. Robert Mitchell is an MIT graduate with over 40 years experience in Informaon Technology and is semirered. He has developed soware for all the big iron companies: IBM, Amdahl, Fujitsu, Naonal Semiconductor, and Storage Technology. Soware companies include Veritas and Symantec. Recent languages that he knows are Ruby and Java, with a long background in C++. www.traintelco.com www.PacktPub.com Support les, eBooks, discount offers and more You might want to visit www.PacktPub.com for support les and downloads related to your book. Did you know that Packt oers eBook versions of every book published, with PDF and ePub les available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collecon of free technical arcles, sign up for a range of free newsleers and receive exclusive discounts and oers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's enre library of books. Why Subscribe? Fully searchable across every book published by Packt Copy and paste, print and bookmark content On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine enrely free books. Simply use your login credenals for immediate access. www.traintelco.com Table of Contents Preface 1 Chapter 1: Seng Up your Environment 7 Geng started with Android development 7 Seng up Windows 8 Time for acon – preparing Windows for Android development 8 Installing Android development kits on Windows 12 Time for acon – installing Android SDK and NDK on Windows 13 Seng up Mac OS X 18 Time for acon – preparing Mac OS X for Android development 18 Installing Android development kits on Mac OS X 20 Time for acon – installing Android SDK and NDK on Mac OS X 20 Seng up Linux 22 Time for acon – preparing Ubuntu Linux for Android development 22 Installing Android development kits on Linux 27 Time for acon – installing Android SDK and NDK on Ubuntu 27 Seng up the Eclipse development environment 29 Time for acon – installing Eclipse 29 Emulang Android 33 Time for acon – creang an Android virtual device 33 Developing with an Android device on Windows and Mac OS X 37 Time for acon – seng up your Android device on Windows and Mac OS X 37 Developing with an Android device on Linux 39 Time for acon – seng up your Android device on Ubuntu 39 Troubleshoong a development device 42 Summary 43 Chapter 2: Creang, Compiling, and Deploying Nave Projects 45 Compiling and deploying NDK sample applicaons 46 Time for acon – compiling and deploying the hellojni sample 46 www.traintelco.com Table of Contents [ ii ] Exploring Android SDK tools 51 Android debug bridge 51 Project conguraon tool 54 Creang your rst Android project using eclipse 56 Time for acon – iniang a Java project 56 Introducing Dalvik 59 Interfacing Java with C/C++ 60 Time for acon – calling C code from Java 60 More on Makeles 65 Compiling nave code from Eclipse 67 Time for acon – creang a hybrid Java/C/C++ project 67 Summary 72 Chapter 3: Interfacing Java and C/C++ with JNI 73 Working with Java primives 74 Time for acon – building a nave key/value store 75 Referencing Java objects from nave code 85 Time for acon – saving a reference to an object in the Store 85 Local and global JNI references 90 Throwing excepons from nave code 91 Time for acon – raising excepons from the Store 92 JNI in C++ 96 Handling Java arrays 96 Time for acon – saving a reference to an object in the Store 97 Checking JNI excepons 106 Summary 107 Chapter 4: Calling Java Back from Nave Code 109 Synchronizing Java and nave threads 110 Time for acon – running a background thread 111 Aaching and detaching threads 120 More on Java and nave code lifecycles 121 Calling Java back from nave code 122 Time for acon – invoking Java code from a nave thread 122 More on callbacks 133 JNI method denions 134 Processing bitmaps navely 135 Time for acon – decoding camera feed from nave code 136 Summary 146 Chapter 5: Wring a Fully-nave Applicaon 147 Creang a nave acvity 148 Time for acon – creang a basic nave acvity 148 www.traintelco.com Table of Contents [ iii ] Handling acvity events 155 Time for acon – handling acvity events 155 More on Nave App Glue 166 UI thread 167 Nave thread 168 Android_app structure 170 Accessing window and me navely 171 Time for acon – displaying raw graphics and implemenng a mer 172 More on me primives 181 Summary 181 Chapter 6: Rendering Graphics with OpenGL ES 183 Inializing OpenGL ES 184 Time for acon – inializing OpenGL ES 184 Reading PNG textures with the asset manager 193 Time for acon – loading a texture in OpenGL ES 194 Drawing a sprite 208 Time for acon – drawing a Ship sprite 209 Rendering a le map with vertex buer objects 220 Time for acon – drawing a le-based background 221 Summary 238 Chapter 7: Playing Sound with OpenSL ES 239 Inializing OpenSL ES 241 Time for acon – creang OpenSL ES engine and output 241 More on OpenSL ES philosophy 248 Playing music les 249 Time for acon – playing background music 249 Playing sounds 256 Time for acon – creang and playing a sound buer queue 257 Event callback 266 Recording sounds 268 Summary 272 Chapter 8: Handling Input Devices and Sensors 273 Interacng with Android 274 Time for acon – handling touch events 276 Detecng keyboard, D-Pad, and Trackball events 288 Time for acon – handling keyboard, D-Pad, and trackball, navely 289 Probing device sensors 298 Time for acon – turning your device into a joypad 300 Summary 313 www.traintelco.com [...]... "$JAVA_HOME"` ANDROID_ SDK=`cygpath –u " $ANDROID_ SDK"` ANDROID_ NDK=`cygpath –u " $ANDROID_ NDK"` [4] www.traintelco.com Preface When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: ... Android development kits on Windows Once JDK is installed on our system, we can start installing Android SDK and NDK to create, compile, and debug Android programs [ 12 ] www.traintelco.com Chapter 1 Time for action – installing Android SDK and NDK on Windows 1 Open your Web browser and go to http://developer .android. com/sdk This web page lists all available SDKs, one for each platform 2 Download Android. .. Android SDK for Windows, packaged as an Exe installer 3 Then, go to http://developer .android. com/sdk/ndk and download the Android NDK (not SDK!) for Windows, packaged as a ZIP archive this time 4 Execute Android SDK installer Select an appropriate installation location (for example, C: \Android\ android-sdk), knowing that Android SDK and NDK together can take more than 3 GB of disk space (currently!) with... (be careful, this is a hidden file!) in your home directory and add the following variables: export ANDROID_ SDK=”” export ANDROID_ NDK=”” export PATH=”$PATH: $ANDROID_ SDK/tools: $ANDROID_ SDK/platformtools: $ANDROID_ NDK” Downloading the example code You can download the example code files for all Packt books you have purchased from your... binary language like English, having an OS is not enough We also need software dedicated to Android development: The JDK (Java Development Kit) The Android SDK (Software Development Kit) The Android NDK (Native Development Kit) An IDE (Integrated Development Environment): Eclipse Android, and more specifically Android NDK compilation system is heavily based on Linux So we also need to set up some... variables: 11 Open the Environment Variables system window, as we did in the previous part Inside the System variables list, insert the ANDROID_ SDK and ANDROID_ NDK variables with the corresponding directories as values 12 Append %ANDROID_ SDK%\tools, %ANDROID_ SDK%\platform-tools and %ANDROID_ NDK%, all separated by a semicolon, to your PATH [ 14 ] www.traintelco.com Chapter 1 13 All the Windows environment variables... –u “$ANT_HOME”` JAVA_HOME=`cygpath –u “$JAVA_HOME”` ANDROID_ SDK=`cygpath –u “ $ANDROID_ SDK”` ANDROID_ NDK=`cygpath –u “ $ANDROID_ NDK”` [ 15 ] www.traintelco.com Setting Up your Environment 17 Reopen a Cygwin window and check the Ant version again No warning is issued this time: $ ant -version What just happened? We have downloaded and deployed both Android SDK and NDK and made them available through command... is not required for Android development but is a very good solution to set up a continuous integration chain [ 19 ] www.traintelco.com Setting Up your Environment Installing Android development kits on Mac OS X Once a JDK is installed on your system, we can start installing Android Development SDK and NDK to create, compile, and debug Android programs Time for action – installing Android SDK and NDK... /Developer/AndroidSDK and /Developer/AndroidNDK) 5 Let’s declare these two directories as environment variables From now on, we will refer to these directories as $ANDROID_ SDK and $ANDROID_ NDK throughout this book Assuming you use the default Bash command-line shell, create or edit your profile file (be careful, this is a hidden file!) in your home directory and add the following variables: export ANDROID_ SDK=” . encoding="utf-8"?> <manifest xmlns :android= "http://schemas .android. com/apk/res /android& quot; package="com.example.hellojni" android: versionCode="1" android: versionName="1.0"> Any. Eclipse 29 Emulang Android 33 Time for acon – creang an Android virtual device 33 Developing with an Android device on Windows and Mac OS X 37 Time for acon – seng up your Android device on. JAVA_HOME=`cygpath –u "$JAVA_HOME"` export ANDROID_ SDK=`cygpath –u " $ANDROID_ SDK"` export ANDROID_ NDK=`cygpath –u " $ANDROID_ NDK"` www.traintelco.com Preface [ 5 ] When