Companion eBooCkompanion eBook Available 488 CHAPTER 9: Super Jumper: A 2D OpenGL ES Game Available Your reference guide for rapidly understanding Android Your reference guide for rapidly understanding Android The rTeal-hweo rreldal -cwoodreld e xcaomdep leexsa fmoupnleds ifno uAnndd rioni dA Rnedcroipides R: Aec Piproesb: leAm P-rSooblluetmio-nS olution A and raanpdid rlayp didelvye dloepvienlgo pAinndgr Aoindd aropipds apps Approach take the time and stress out of developing top-notch apps for this A Approach take the time and stress out of developing top-notch apps for this leading mobile OS platform. When you start a new project, just copy and paste the codlee aadnidn gc omnofigbuilera OtioS np flailetfso frrmom. W thheen b oyoouk, stthaernt ata nileowr t po ryoojeucrt n, jeuesdt .c opy and paste n the code and configuration files from the book, then tailor to your need. n Using complete and tested code examples, Android Recipes features a host of d Using complete and tested code examples, Android Recipes features a host of d solutions to practical problems. Study it chapter by chapter, or dip into its more solutions to practical problems. Study it chapter by chapter, or dip into its more than 80 down-to-earth recipes to find the exact solution you need as you need it. than 80 down-to-earth recipes to find the exact solution you need as you need it. r r Android Recipes teaches you how to build an app with Google’s Android SDK at o Android Recipes teaches you how to build an app with Google’s Android SDK at o the command line or the graphical Eclipse IDE. From there, you’ll rapidly master the command line or the graphical Eclipse IDE. From there, you’ll rapidly master the user interface, cloud communications, device hardware, data persistence, i the user interface, cloud communications, device hardware, data persistence, i inter-app communications, and interaction with Android itself. d inter-app communications, and interaction with Android itself. d What you’ll learn • AnWdrh•oa itd y aorcuh’lilt leecatrunre and various Android-specific APIs R • Android architecture and various Android-specific APIs R How• to develop a Units Converter app in the context of command-line/ How to develop a Units Converter app in the context of command-line/ Android SDK and Eclipse/Android SDK environments • How• to A ancdcoromidp lSisDhK v aanrido uEcsl tipasskes/A renldartoeidd t SoD tKh ee nuvseirro innmteerfnatcse and more ee • How to accomplish various tasks related to the user interface and more How• to use external libraries to save time and effort c • How• to H qouwic tkoly u dseev eexltoepr naanl alipbpra uriseins gto t hsaev Sec triimptein agn Lda eyfefor r4t Android tool c •• HGuowid•• eto liHHG nbuooeowwisdo f seotttoolr ia nfqbpieluotpseoi c fprsoketerl dya rf,f pid olptpereem vprreefeaoldronr,fmp cope raea mbnrnfy atoa ,nu rprmcsepeisn a upbgnsoy titnn ,hu rsgesei vi stnAehpgn,eo sdt nSehrscaoeirmvi iAdpel n,etN isdsnDesrga oKa mLipdapl eyNsesDsr Ka4p Apnsdroid tool ipip From insightful instruction to helpful examples, Android Recipes is your guide to e From insightful instruction to helpful examples, Android Recipes is your guide to e writing cool, popular apps for one of today’s hottest mobile platforms. Android Recipes writing cool, popular apps for one of today’s hottest mobile platforms. Android Recipes s s A Problem-Solution Approach A Problem-Solution Approach F Dave Smith | Jeff Friesen rieSmFrS Dave Smith | Jeff Friesen seitiesm nheit nh 488 CHAPTER 9: Super Jumper: A 2D OpenGL ES Game For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Contents at a Glance Contents ............................................................................................................. iv Foreword ......................................................................................................... viii About the Authors .............................................................................................. ix About the Technical Reviewer ............................................................................ x Acknowledgments ............................................................................................. xi Preface ............................................................................................................. xii ■Chapter 1: Getting Started with Android ......................................................... 1(cid:1) ■Chapter 2: User Interface Recipes ................................................................. 75(cid:1) ■Chapter 3: Communications and Networking .............................................. 155(cid:1) ■Chapter 4: Interacting with Device Hardware and Media ........................... 201(cid:1) ■Chapter 5: Persisting Data .......................................................................... 257(cid:1) ■Chapter 6: Interacting with the System ...................................................... 309(cid:1) ■Chapter 7: Working with Libraries .............................................................. 353(cid:1) ■Appendix A: Scripting Layer for Android ..................................................... 385(cid:1) ■Appendix B: Android NDK ............................................................................ 397(cid:1) ■Appendix C: App Design Guidelines ............................................................. 411(cid:1) Index ............................................................................................................... 419 iii 1 1 Chapter Getting Started with Android Android is hot, and many people are developing Android applications (apps for short). Perhaps you would also like to develop apps, but are unsure about how to get started. Although you could study Google’s online Android Developer’s Guide (http://developer.android.com/guide/index.html) to acquire the needed knowledge, you might be overwhelmed by the vast amount of information that this guide presents. In contrast, this chapter provides just enough theory to help you understand the basics of Android. This theory is followed by several recipes that teach you how to develop apps and prepare them for publication to Google’s Android Market. What Is Android? The Android Developer’s Guide defines Android as a software stack – a set of software subsystems needed to deliver a fully functional solution – for mobile devices. This stack includes an operating system (a modified version of the Linux kernel), middleware (software that connects the low-level operating system to high-level apps) that’s partly based on Java, and key apps (written in Java) such as a web browser (known as Browser) and a contact manager (known as Contacts). Android offers the following features: (cid:1) Application framework enabling reuse and replacement of app components (discussed later in this chapter) (cid:1) Bluetooth, EDGE, 3G, and WiFi support (hardware dependent) (cid:1) Camera, GPS, compass, and accelerometer support (hardware dependent) (cid:1) Dalvik Virtual Machine (DVM) optimized for mobile devices (cid:1) GSM Telephony support (hardware dependent) 1 2 CHAPTER 1: Getting Started with Android (cid:1) Integrated browser based on the open source WebKit engine (cid:1) Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) (cid:1) Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) (cid:1) SQLite for structured data storage Although not part of an Android device’s software stack, Android’s rich development environment (including a device emulator and a plugin for the Eclipse IDE) could also be considered an Android feature. History of Android Contrary to what you might expect, Android did not originate with Google. Instead, Android was initially developed by Android, Inc., a small Palo Alto, California-based startup company. Google bought this company in July 2005 and released a preview version of the Android SDK in November 2007. In mid-August, 2008, Google released the Android 0.9 SDK beta, and subsequently released the Android 1.0 SDK one month later. Table 1–1 outlines subsequent SDK update releases. (Starting with version 1.5, each major release comes under a code name that’s based on a dessert item.) Table 1–1. Android Update Releases SDK Update Release Date and Changes 1.1 Google released SDK 1.1 on February 9, 2009. Changes included paid apps (via Android Market) and “search by voice” support. 1.5 (Cupcake) Google released SDK 1.5 on April 30, 2009. Changes included the ability to Based on Linux record and watch videos through camcorder mode, the ability to upload Kernel 2.6.27 videos to YouTube and pictures to Picasa, the ability to populate the home screen with widgets, and animated screen transitions. 1.6 (Donut) Google released SDK 1.6 on September 15, 2009. Changes included an Based on Linux improved Android Market experience, an integrated Kernel 2.6.29 camera/camcorder/gallery interface, updated “search by voice” with speed and other improvements, and an updated search experience. 2.0/2.1 (Eclair) Google released SDK 2.0 on October 26, 2009. Changes included a Based on Linux revamped user interface, a new contacts list, support for Microsoft Kernel 2.6.29 Exchange, digital zoom, improved Google Maps (version 3.1.2), HTML5 support for the Browser app, live wallpapers, and Bluetooth 2.1 support. Google subsequently released SDK update 2.0.1 on December 3, 2009, and SDK update 2.1 on January 12, 2010. CHAPTER 1: Getting Started with Android 3 SDK Update Release Date and Changes 2.2 (Froyo) Google released SDK 2.2 on May 20, 2009. Changes included the Based on Linux integration of Chrome’s V8 JavaScript engine into the Browser app, voice Kernel 2.6.32 dialing and contact sharing over Bluetooth, Adobe Flash 10.1 support, additional app speed improvements courtesy of a JIT implementation, and USB tethering and WiFi hotspot functionality. 2.3 (Gingerbread) Google released SDK 2.3 on December 6, 2010. Changes included a new Based on Linux concurrent garbage collector that improves an app’s responsiveness, Kernel 2.6.35.7 support for gyroscope sensing, support for WebM video playback and other video improvements, support for near field communication, and improved social networking features. This book focuses on Android 2.3. Google subsequently released SDK 2.3.1 to fix some bugs, and SDK 2.3.3, a small feature release that adds several improvements and APIs to the Android 2.3 platform. 3.0 (Honeycomb) Google released SDK 3.0 on February 22, 2011. Unlike previous releases, Based on Linux version 3.0 focuses exclusively on tablets, such as Motorola Zoom, the first 2.6.36 tablet to be released (on February 24, 2011). In addition to an improved user interface, version 3.0 improves multitasking, supports multicore processors, supports hardware acceleration, and provides a 3D desktop with redesigned widgets. Android Architecture The Android software stack consists of apps at the top, middleware (consisting of an application framework, libraries, and the Android runtime) in the middle, and a Linux kernel with various drivers at the bottom. Figure 1–1 shows this layered architecture. 4 CHAPTER 1: Getting Started with Android Figure 1–1. Android’s layered architecture consists of several major parts. Users care about apps, and Android ships with a variety of useful core apps, which include Browser, Contacts, and Phone. All apps are written in the Java programming language. Apps form the top layer of Android’s architecture. Directly beneath the app layer is the application framework, a set of high-level building blocks for creating apps. The application framework is preinstalled on Android devices and consists of the following components: (cid:1) Activity Manager: This component provides an app’s lifecycle and maintains a shared activity stack for navigating within and among apps. Both topics are discussed later in this chapter. (cid:1) Content Providers: These components encapsulate data (such as the Browser app’s bookmarks) that can be shared among apps. (cid:1) Location Manager: This component makes it possible for an Android device to be aware of its physical location. CHAPTER 1: Getting Started with Android 5 (cid:1) Notification Manager: This component lets an app notify the user of a significant event (such as a message’s arrival) without interrupting what the user is currently doing. (cid:1) Package Manager: This component lets an app learn about other app packages that are currently installed on the device. (App packages are discussed later in this chapter.) (cid:1) Resource Manager: This component lets an app access its resources, a topic that’s briefly discussed in Recipe 1–5. (cid:1) Telephony Manager: This component lets an app learn about a device’s telephony services. It also handles making and receiving phone calls. (cid:1) View System: This component manages user interface elements and user interface-oriented event generation. (These topics are briefly discussed in Recipe 1–5.) (cid:1) Window Manager: This component organizes the screen’s real estate into windows, allocates drawing surfaces, and performs other window- related jobs. The components of the application framework rely on a set of C/C++ libraries to perform their jobs. Developers interact with the following libraries by way of framework APIs: (cid:1) FreeType: This library supports bitmap and vector font rendering. (cid:1) libc: This library is a BSD-derived implementation of the standard C system library, tuned for embedded Linux-based devices. (cid:1) LibWebCore: This library offers a modern and fast web browser engine that powers the Android browser and an embeddable web view. It’s based on WebKit (http://en.wikipedia.org/wiki/WebKit) and is also used by the Google Chrome and Apple Safari browsers. (cid:1) Media Framework: These libraries, which are based on PacketVideo’s OpenCORE, support the playback and recording of many popular audio and video formats, as well as working with static image files. Supported formats include MPEG4, H.264, MP3, AAC, AMR, JPEG, and PNG. (cid:1) OpenGL | ES: These 3D graphics libraries provide an OpenGL implementation based on OpenGL | ES 1.0 APIs. They use hardware 3D acceleration (where available) or the included (and highly optimized) 3D software rasterizer. (cid:1) SGL: This library provides the underlying 2D graphics engine. (cid:1) SQLite: This library provides a powerful and lightweight relational database engine that’s available to all apps, and that’s also used by Mozilla Firefox and Apple’s iPhone for persistent storage. 6 CHAPTER 1: Getting Started with Android (cid:1) SSL: This library provides secure sockets layer-based (SSL-based) security for network communication. (cid:1) Surface Manager: This library manages access to the display subsystem, and seamlessly composites 2D and 3D graphic layers from multiple apps. Android provides a runtime environment that consists of core libraries (implementing a subset of the Apache Harmony Java version 5 implementation) and the Dalvik Virtual Machine (DVM), a non-Java virtual machine that’s based on processor registers instead of being stack-based. NOTE: Google’s Dan Bornstein created Dalvik and named this virtual machine after an Icelandic fishing village where some of his ancestors lived. Each Android app defaults to running in its own Linux process, which hosts an instance of Dalvik. This virtual machine has been designed so that devices can run multiple virtual machines efficiently. This efficiency is largely due to Dalvik executing Dalvik Executable (DEX)-based files – DEX is a format that’s optimized for a minimal memory footprint. NOTE: Android starts a process when any of part of the app needs to execute, and shuts down the process when it’s no longer needed and system resources are required by other apps. Perhaps you’re wondering how it’s possible to have a non-Java virtual machine run Java code. The answer is that Dalvik doesn’t run Java code. Instead, Android transforms compiled Java classfiles into the DEX format, and it’s this resulting code that gets executed by Dalvik. Finally, the libraries and Android runtime rely on the Linux kernel (version 2.6) for underlying core services such as threading, low-level memory management, a network stack, process management, and a driver model. Furthermore, the kernel acts as an abstraction layer between the hardware and the rest of the software stack. ANDROID SECURITY MODEL Android’s architecture includes a security model that prevents apps from performing operations considered harmful to other apps, Linux, or users. This security model, which is mostly based on process level enforcement via standard Linux features (such as user and group IDs), places processes in a security sandbox. By default, the sandbox prevents apps from reading or writing the user’s private data (such as contacts or emails), reading or writing another app’s files, performing network access, keeping the device awake, accessing the camera, and so on. Apps that need to access the network or perform other sensitive operations must first obtain permission to do so. CHAPTER 1: Getting Started with Android 7 Android handles permission requests in various ways, typically by automatically allowing or disallowing the request based upon a certificate, or by prompting the user to grant or revoke the permission. Permissions required by an app are declared in the app’s manifest file (discussed later in this chapter) so that they are known to Android when the app is installed. These permissions won’t subsequently change. App Architecture The architecture of an Android app differs from desktop application architecture. App architecture is based upon components that communicate with each other by using intents that are described by a manifest and that are stored in an app package. Components An app is a collection of components (activities, services, content providers, and broadcast receivers) that run in a Linux process and that are managed by Android. These components share a set of resources, including databases, preferences, a filesystem, and the Linux process. NOTE: Not all of these components need to be present in an app. For example, one app might consist of activities only, whereas another app might consist of activities and a service. This component-oriented architecture lets an app reuse the components of other apps, provided that those other apps permit reuse of their components. Component reuse reduces overall memory footprint, which is very important for devices with limited memory. To make the reuse concept concrete, suppose you’re creating a drawing app that lets users choose a color from a palette, and suppose that another app has developed a suitable color chooser and permits this component to be reused. In this scenario, the drawing app can call upon that other app’s color chooser to have the user select a color rather than provide its own color chooser. The drawing app doesn’t contain the other app’s color chooser or even link to this other app. Instead, it starts up the other app’s color chooser component when needed. Android starts a process when any part of the app (such as the aforementioned color chooser) is needed, and instantiates the Java objects for that part. This is why Android’s apps don’t have a single entry point (no C-style main() function, for example). Instead, apps use components that are instantiated and run as needed. Activities An activity is a component that presents a user interface so that the user can interact with an app. For example, Android’s Contacts app includes an activity for entering a
Description: