28,99 €
Unleash the power of the Android OS and build the kinds of brilliant, innovative apps users love to use If you already know your way around the Android OS and can build a simple Android app in under an hour, this book is for you. If you're itching to see just how far you can push it and discover what Android is really capable of, it's for you. And if you're ready to learn how to build advanced, intuitive, innovative apps that are a blast to use, this book is definitely for you. From custom views and advanced multi-touch gestures, to integrating online web services and exploiting the latest geofencing and activity recognition features, ace Android developer, Erik Hellman, delivers expert tips, tricks and little-known techniques for pushing the Android envelope so you can: * Optimize your components for the smoothest user experience possible * Create your own custom Views * Push the boundaries of the Android SDK * Master Android Studio and Gradle * Make optimal use of the Android audio, video and graphics APIs * Program in Text-To-Speech and Speech Recognition * Make the most of the new Android maps and location API * Use Android connectivity technologies to communicate with remote devices * Perform background processing * Use Android cryptography APIs * Find and safely use hidden Android APIs * Cloud-enable your applications with Google Play Services * Distribute and sell your applications on Google Play Store Learn how to unleash the power of Android and transform your apps from good to great in Android Programming: Pushing the Limits.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 558
Veröffentlichungsjahr: 2013
This edition first published 2014
© 2014 Erik Hellman
Registered office
John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom
For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com.
The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988.
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required, the services of a competent professional should be sought.
Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley and Sons, Inc. and/ or its affiliates in the United States and/or other countries, and may not be used without written permission. Android is a trademark of Google, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Ltd. is not associated with any product or vendor mentioned in the book.
A catalogue record for this book is available from the British Library.
ISBN 978-1-118-71737-0 (paperback); ISBN 978-1-118-71730-1 (ePDF); 978-1-118-71735-6 (ePub)
Set in 9.5 pt Myriad Pro by Indianapolis Composition Services
Printed in the United States by Bind-Rite
Dedication
This book is dedicated to my amazing dad, Ingemar Hellman, who taught me programming when I was nine years old. None of this would have been possible if it weren’t for all the amazing things he taught me.
Erik Hellman, Second generation software developer
Publisher’s Acknowledgements
Some of the people who helped bring this book to market include the following:
Editorial and Production
VP Consumer and Technology Publishing Director: Michelle Leete
Associate Director–Book Content Management: Martin Tribe
Associate Publisher: Chris Webb
Project Editor: M. Faunette Johnston
Copy Editor: Melba Hopper
Technical Editor: Erik Westenius
Editorial Manager: Jodi Jensen
Senior Project Editor: Sara Shlaer
Editorial Assistant: Annie Sullivan
Marketing
Associate Marketing Director: Louise Breinholt
Marketing Manager: Lorna Mein
Senior Marketing Executive: Kate Parrett
Marketing Assistant: Polly Thomas
Composition Services
Compositor: Jennifer Goldsmith, Andrea Hornberger
Proofreader: Wordsmith Editorial
Indexer: Potomac Indexing, LLC
About the Author
Erik Hellman grew up in the small town of Borlänge in the middle of Sweden and currently lives in the city of Malmö with his wife. From an early age he showed a great interest in all kinds of technology, much thanks to his father. This interest has carried on over the years and he likes to spend time tinkering with all kinds of technology, be it hardware or software.
Erik currently works as a developer consultant at Factor10. He previously worked for Sony Mobile as one of the lead architects for their Android development and later as a research engineer where he participated in the development of the next generation of mobile solutions from Sony.
Erik has a lifetime of experience with software development and programming. His father taught him how to write code in Turbo Pascal at the age of nine, as well as how to design relational databases in Oracle 3 on his old IBM AT 286. Much later, Erik studied Software Engineering at Blekinge Institute of Technology where he also worked as an assistant teacher in various software engineering courses.
Erik can often be found at various developer conferences where he likes to speak about cutting-edge software technologies. You can also find out more about Erik and his other hobbies at his blog (http://blog.hellsoft.se) or follow him on Google+ (http://gplus.to/ErikHellman) or Facebook (https://www.facebook.com/ErikHellman).
Acknowledgements
First of all, I’d like to thank my wife Kaisa-Leena. Without her love, support, and infinite patience with me during the writing of this book, this book would never have been finished.
A big thank you goes out to all my friends and former colleagues at Sony Mobile. Almost everything I’ve learned about Android and mobile technologies came from my years working with all of you. I’m extremely proud to have been part of the team that built the Xperia series of devices. A special thank you to my former boss, Henrik Bengtsson, and his team at the Sony Mobile Research in Lund.
Finally, I’d like to thank my editors; Faunette, Melba, Erik, and all the people working at Wiley for helping me write this book. A big thanks goes to my technical editor Erik Westenius for his eye for details and making sure that my code and examples are understandable. Also, a thank you to Kristoffer Åberg at Sony Mobile for giving me valuable input on the UI design sections.
Table of Contents
Introduction
Who This Book Is For
What This Book Covers
How This Book Is Structured
Part I: Building a Better Foundation
Part II: Getting the Most Out of Components
Part III: Pushing the Limits
What You Need to Use This Book
Source Code
Errata
Part I: Building a Better Foundation
Chapter 1: Fine-Tuning Your Development Environment
Operating Systems for Android Development
Advanced Android SDK Tools
The adb Tool
Stress-Testing an Application’s UI with Monkey
Optimize and Obfuscate with ProGuard
Android Library Projects and Third-Party Libraries
Precompiled JAR Libraries
Setting Up a Library Project
Version Control and Source Code Management
Mastering Your IDE
Debugging Android Applications
Static Code Analysis with lint
Refactoring Your Code
Developer Options on Android Devices
Understanding Developer Settings
Summary
Further Resources
Websites
Chapter 2: Efficient Java Code for Android
Comparing Android’s Dalvik Java to Java SE
Optimizing Java Code for Android
Type-Safe Enum on Android
Enhanced For-Loop on Android
Queues, Synchronization, and Locks
Memory Management and Allocations
Reducing Object Allocations
Multithreading on Android
Thread
AsyncTask
Handler
Picking the Right Solution for Threads
Summary
Further Resources
Books
Online Sources
Part II: Getting the Most Out of Components
Chapter 3: Components, Manifests, and Resources
Android Components
The Activity Component
The Service Component
The BroadcastReceiver Component
The ContentProvider Component
The Application Component
Application Architecture
The Android Application Manifest
The Manifest Element
Google Play Filters and Permissions
The Application Element
Component Elements and Attributes
Intent Filtering
Resources and Assets
Advanced String Resources
Localization
Using Resource Qualifiers
Using Assets
Summary
Further Resources
Chapter 4: Android User Experience and Interface Design
User Stories
Understanding the User with Personas
Android UI Design
Navigation
Prototyping User Interfaces
Android UI Elements
Text in Android Applications
Font Matters
Text Layout
Dimensions and Sizes
Recommended Dimensions
Icon Sizes
Text Size
Colors
Color Blindness
Images and Icons
Canonical Perspective
Geons
Recognizing Faces
Usability
Visual Cues
Rewarding the User
Gamification
Summary
Further Resources
Chapter 5: Android User Interface Operations
Activities and Fragments
Using Multiple Screens
Designing Custom Views
View Life Cycle
Piano Keyboard Widget
Multi-Touching
PointerCoordinates
Rotate Gesture
OpenGL ES
Scene Graphs and Graphics Engines
Summary
Further Resources
Books
Chapter 6: Services and Background Tasks
When and How to Use a Service
Service Types
Understanding the Service Lifecycle
Service Creation and Destruction
Starting Services
Binding Services
Staying Alive
Stopping Services
Running in the Background
IntentService
Parallel Execution
Communicating with Services
Asynchronous Messaging with Intents
Locally Bound Services
Summary
Further Resources
Blogs
Chapter 7: Android IPC
The Binder Explained
Binder Address
Binder Transactions
Parcel
Link to Death
Designing APIs
AIDL
Messenger
Wrapping APIs with Library Projects
Securing Remote APIs
Summary
Further Resources
Chapter 8: Mastering BroadcastReceivers and Configuration Changes
BroadcastReceivers
Local BroadcastReceivers
Normal and Ordered Broadcasts
Sticky Broadcasts
Directed Broadcasts
Enabling and Disabling Receivers
System Broadcast Intents
Device Configuration Changes
Summary
Further Resources
Chapter 9: Data Storage and Serialization Techniques
Persistence Options for Android
Storing Data in Preference Files
User Options and Settings UI
High-Performance ContentProviders
Android Database Design
Creating and Upgrading Databases
Implementing Query Methods
Database Transactions
Storing Binary Data in ContentProvider
Serializing Data for Persistence
JavaScript Object Notation
Advanced JSON Handling with Gson
Google Protocol Buffers
Application Data Backup
Summary
Further Resources
Websites
Chapter 10: Writing Automated Tests
Android Testing Principles
What to Test
Basic Unit Testing
Testing Activities
Testing Services
Testing ContentProviders
Running Tests
Continuous Integration
Summary
Further Resources
Books
Websites
Part III: Pushing the Limits
Chapter 11: Advanced Audio, Video, and Camera Applications
Advanced Audio Applications
Low-Latency Audio
OpenSL ES for Android
Text-to-Speech (TTS)
Speech Recognition
Video Processing with OpenGL ES 2.0
Camera Processing with OpenGL ES 2.0
Encoding Media
Recording an OpenGL Scene
Summary
Further Resources
Chapter 12: Secure Android Applications
Android Security Concepts
Signatures and Keys
Android Permissions
Protecting User Data
Verifying Calling Applications
Client-Side Data Encryption
Android Crypto API
Generating a Key
Encrypting Data
Decrypting Data
Working with Encrypted Data
Android Key Chain Management
Device Management API
Summary
Further Resources
Documentation
Websites
Chapter 13: Maps, Location, and Activity APIs
Fused Location Manager
Google Maps v2 Integration
Working with Google Maps
Markers on Maps
Drawing Circles
Drawing Polygons
Useful Location API Utilities
Geocoding
Using the LocationClient
Geofencing
Activity Recognition
Summary
Further Resources
Documentation
Chapter 14: Native Code and JNI
A Note on CPU Architecture
Writing Android Applications in C
Android NDK Build Scripts
Native Activities
Working with JNI
Calling Native Functions from Java
Calling a Java Method from Native
Android Native APIs
The C Library
Native Android Logging
Native OpenGL ES 2.0
Native Audio with OpenSL ES
Porting a Native Library to Android
Building a Native Library
Summary
Further Resources
Oracle Websites
Chapter 15: The Hidden Android APIs
Official and Hidden APIs
Discovering Hidden APIs
Safely Calling Hidden APIs
Extracting Hidden APIs from a Device
Calling Hidden APIs Using Reflections
Examples of Hidden APIs
Receiving and Reading SMS
Wi-Fi Tethering
Hidden Settings
Summary
Further Resources
Chapter 16: Hacking the Android Platform
Unlocking Your Device
Flashing Factory Images
Unlocking Non-Google Nexus Devices
Community-Supported Firmwares
The Android Source Code
Setting Up the Build Environment
Building and Flashing
Writing System Applications
Platform Certificates
Writing Signature-Signed Applications
Hacking the Android Platform
Setting Up Your IDE
Android Projects
Android Linux Kernel
Adding a System Service
Speeding Up the Platform Development Cycle
Contributing to AOSP
Summary
Further Resources
Chapter 17: Networking, Web Service, and Remote APIs
Android Networking
HttpUrlConnection
Volley
OkHttp and SPDY
Web Sockets
Integrating Web Services
Google Static Maps v2
Foursquare API Using OAuth2
Facebook SDK for Android
Finding Online Web Services and APIs
Network and Power Consumption
General Guidelines
Power Efficient Network Polling
Server-Side Push
Summary
Further Resources
Chapter 18: Communicating with Remote Devices
Android’s Connectivity Technologies
Android USB
Bluetooth Low Energy
Android Wi-Fi
Network Service Discovery
WiFi Direct
On-Device Web Services
RESTful with Restlet
Web Socket Server
Summary
Further Resources
Chapter 19: Google Play Services
Authorization
Google Drive Application Data
Google Cloud Endpoints
Google Cloud Messaging
GCM Client
Google Play Game Services
Data Messaging
Messaging Strategy
Summary
Further Resources
Chapter 20: Distributing Applications on Google Play Store
In-app Billing
Consuming Products
In-app Subscriptions
Ads in Android Applications
Targeting Ads
Ad Colors
Interstitial Ads
Application Licensing
APK Expansion Files
Creating Expansion Files
Downloading Expansion Files
Summary
Further Resources
Introduction
If you’re reading this book, you’re probably familiar with the Android platform, smartphones, and application development. You’re well aware of the tremendous growth of Android devices over the last few years and the potential that the platform holds for application developers. I could give you specific numbers and statistics about Android, but that wouldn’t serve much purpose because those numbers most likely would be invalid by the time you read this book. It’s enough to say that the Android platform is here to stay, and you can expect its growth to continue for the foreseeable future.
All of this is great news to people like you and me. Those of us who are aiming to becoming experts at Android development face a bright future. The demand for skilled application developers for Android is growing every day, and at the same time, the demand on developers is growing because the features that users want and the possibilities provided by the new technologies require us to constantly think ahead.
Although Google provides a great set of tools and APIs to help you perform your magic, you still need to push yourself on what you can now do with Android. That is the goal of this book: to push the limits of the Android platform and build ever more advanced applications.
Who This Book Is For
You’ve probably written a few Android applications already and are eager to learn more advanced APIs and tricks. Perhaps you generally program using Java, but you don’t have any problems learning a new language. As a developer, you’re not afraid to try out new things, be it a new IDE or a brand new API. You like to test all the latest features, and you don’t’ become discouraged when things initially fail.
While you can find plenty of introductory books on Android development, this is not such a book. Instead, this book is targeted toward developers who have previous experience with application development for Android. You know all the basics and how to create an app using the Activity, Service, BroadcastReceiver, and ContentProvider classes. You’re familiar with the core concept of the application manifest and the different types of application resources for Android. If you can build a simple Android application in a matter of minutes, you’re well prepared for the contents of this book.
My goal for this book is just what the title says: pushing the limits. In each chapter, I try to push the limits on what typical Android developers know and use in their daily work. Even though you may be familiar with some of this book’s topics, I provide an in-depth discussion on each topic; so, trust me, there’s something new for all Android developers in this book.
What This Book Covers
The Android platforms have developed at an amazing pace. Even while writing this book, I had to change my original plans because Google kept coming out with new APIs, tools, and technologies for Android developers! While many of the examples in this book require a later version of Android, my assumption is that you are familiar with the different API levels and understand which Android version is required in each case.
My goal is to discuss those aspects of Android that I believe are of value for developers. Some technologies were excluded, either because they aren’t “pushing the limits” or they wouldn’t add real value to the book. So, rather than being a collection of “recipes” for Android applications or an extensive walkthrough of all the features, each chapter goes into the deep technical details of their respective topic. Thus, rather than provide complete applications, I provide numerous pieces of substantial code that you can use to enhance your own applications.
Depending on your experience, you might encounter some unfamiliar technologies. For example, Chapter 12 covers security issues and assumes a basic understanding of encryption and private/public keys, and Chapter 18 covers technologies such as USB communication, Bluetooth Low Energy, and WiFi Direct. But don’t worry. In such cases, I direct you to sources where you can find additional information. Each chapter has a Further Resources section where I’ve listed additional resources such as books and websites where you can find more information on the topics covered in each chapter.
How This Book Is Structured
This book is divided into three parts. The first part covers tools available to Android developers and the specifics on the Java programming language for Android. The second part focuses on core Android components and how to use them in an optimal way. The third and final part focuses on the latest and most advanced technologies, including both the Android platform and the services that can be used with an Android device.
Part I: Building a Better Foundation
Chapter 1: Fine-Tuning Your Development Environment deals with the Android development tools. You’ll find an introduction to the new IDE for Android called Android Studio. There is also a brief introduction to Gradle, which is now used as the standard build system for Android applications.
Chapter 2: Efficient Java Code for Android focuses on the Java programming language and the specifics for Android. I discuss some tricks that can help you reduce the load on memory and on the Dalvik garbage collector. You’ll also find some examples showing the pros and cons of the different methods for multi-threading.
Part II: Getting the Most Out of Components
Chapter 3: Components, Manifests, and Resources gives a general overview of the components and goes on to describe some of the less frequently used parts of the application manifest. You’ll also find examples of advanced use of Android resources.
Chapter 4: Android User Experience and Interface Design focuses on the theory behind the design of user interfaces. I describe how you should work when designing your user interfaces, starting with user stories, personas, and the design-process for the different screens in your application. I explain how people think about, react to, and interpret the various aspects of user interfaces. I describe details about fonts and what makes one font more readable than another. This chapter gives a better understanding of the theories behind good design that you can apply while designing your own interfaces.
Chapter 5: Advanced User Interface Operations focuses on the technical aspects of the Android UI. I show how to use the new APIs with multiple screens in an application. A complete example of how to build a custom View is covered followed by a section on advanced multi-touch handling.
Chapter 6: Services and Background Tasks focuses on how to use the Service component for optimal background operations in your application. This chapter focuses on Services that aren’t published to other applications.
Chapter 7: Android IPC covers Android IPC and how you can communicate between two separate Android applications running on the same device. I explain the details of the Binder and how you can use it to build applications that support plug-in functionality.
Chapter 8: Mastering BroadcastReceivers and Configuration Changes focuses on the use of BroadcastReceivers and how to use them optimally to listen for system-wide events and configuration changes. I describe the different types of broadcasts and how to use them, and I give some guidelines on how to use the receiver component in a way that reduces the load on the device.
Chapter 9: Data Storage and Serialization Techniques focuses on data persistence and on the ContentProvider component. I show how to use the SharedPreferences and how to create a Settings UI using the ready-made Android components. High-performance providers are covered as well as different methods for serializing data where the standard SQLite-based solution isn’t sufficient. Also, the serialization methods explained here are useful when communicating with Services online. I conclude this chapter with some details on how to use the Android backup agent in your application.
Chapter 10: Writing Automated Tests is dedicated to building automated tests for your Android application. I give thorough examples of everything from simple unit tests to complete integration tests for the four different components. I highly recommend that all readers go through this chapter thoroughly because writing tests for your application will greatly improve your development cycle and the quality of your code.
Part III: Pushing the Limits
Chapter 11: Advanced Audio, Video, and Camera Applications deals with advanced graphics, audio, and video. I explain the use of the different audio APIs, including the use of Open SL ES for any high-performance and low-latency requirements you might have regarding audio. I explain the use of both Text-To-Speech and the Speech Recognition API for Android. The use of OpenGL ES for high-performance processing of camera input and video is demonstrated as well. Finally, I discuss a feature introduced in Android 4.3 for using an OpenGL ES surface as an encoding source, which you can employ to record a video of your OpenGL ES scene.
Chapter 12: Secure Android Applications looks at the different security aspects in Android with a focus on how to use the cryptographic APIs. I explain how to use key management in android in a secure way and how to encrypt data on a device. I conclude this chapter with a section covering the Device Management API.
Chapter 13: Maps, Location, and Activity APIs focuses on the new maps and location API for Android. You find out about the new fused Location Provider and how to use features such as geofencing and activity recognition in order to build advanced location-based applications.
Chapter 14: Native Code and JNI delves into native development for Android using the C programming language. I explain the use of the Android NDK (Native Development Kit) and how you can combine native code with Java code through the use of JNI.
Chapter 15: The Hidden Android APIs looks at how the hidden APIs in Android work, how you can find them, and how you can safely invoke them in your application. You also find out how to search the Android source code in order to discover the hidden APIs.
Chapter 16: Hacking the Android Platform describes how to work with the Android Open Source Project (AOSP), build your own custom firmware, and extend the Android platform. I explain how the AOSP is designed and to work when modifying the Android platform. You’ll also find an introduction on the process of contributing your changes to the AOSP so that they can become a standard part of the Android platform.
Chapter 17: Networking, Web Services, and Remote APIs looks at integrating online web services in an Android application and how to optimize network operations. I cover the use of recommended third-party libraries for working with network operations, from standard HTTP to Web Sockets and SPDY, and I explain how to invoke three different types of web services. I explain the concept of authenticating toward third-party web services, including how to use OAuth2 in your Android application as well as how to integrate the Facebook SDK for Android.
Chapter 18: Communicating with Remote Devices delves into the different methods for communicating with remote devices using the various connectivity technologies available on Android. I explain how to talk to USB devices using the built-in APIs in Android. I describe the APIs for communicating with Bluetooth Low Energy devices (also called Bluetooth Smart). You’ll find an introduction on utilizing the network discovery API for Android, and I show how you can implement ad hoc peer-to-peer communication using the WiFi Direct standard. You’ll also find a section on implementing on-device services supporting both RESTful web services and asynchronous communication using Web Sockets.
Chapter 19: Google Play Services covers the use of some of the APIs from Google Play Services. You’ll find out how to get authorization for any of the online Google APIs and an example of using the Application Data feature for Google Drive to store your application’s data across multiple devices. You’ll also find a guide to building Google Cloud Endpoints using the built-in feature in Android Studio, and I show how you can extend this with your own services. This chapter also includes a guide on implementing Google Cloud Messaging. Also, I demonstrate how you can use the real-time multiplayer API that is part of the Google Play Game Services to build advanced multiplayer games.
Chapter 20: Distributing Applications on Google Play Store, the final chapter, focuses on aspects of distributing your application on the Google Play Store and how to include the different monetization options. I explain how to add In-app Billing and ads in your application as well as the use of the licensing service for verifying the license of your application on the user’s device. The chapter ends with a guide to utilizing the APK Expansion Files feature to distribute application data that exceeds your application’s 50MB limit.
What You Need to Use This Book
Although you can run many of the examples in this book on an emulator, I strongly recommend that you acquire a device with the latest version of Android because many examples in the book use hardware that isn’t available on the emulator. Although any Google-certified Android device is sufficient (that is, an Android device with the Google Play Store) for the examples in this book, given that it has the correct Android version, I always recommend purchasing a Google Nexus device so that you can try all the latest platform features as early as possible.
You also need a computer running Linux, OS X, or Windows for your development environment, as well as an Internet connection to access the online resources needed in some chapters. You need to have Java SDK version 6 installed on your computer. (You can download it at http://java.oracle.com) in order to run the IDE and other tools.
In Chapter 18, you’ll need additional hardware to implement the examples. You’ll need a device with Bluetooth Low Energy support, such as an activity tracker or a heartbeat monitor. For the samples on USB communication, you’ll need an Android device that supports USB On-The-Go, a USB OTG cable, and a USB-connected device that you can connect to. The easiest approach to testing USB is to use an Arduino Uno board.
Source Code
Most of the source code samples in this book aren’t complete implementations; rather they are snippets of code I use to demonstrate the most important parts of the topic being covered. My assumption is that you are familiar enough with Android development to understand where to fit these snippets of code into your own project.
Some of the samples and source code snippets in the book are available on my GitHub site (https://github.com/ErikHellman/apptl). However, I strongly recommend that you manually type the code you find in the book instead of simply copying a file. Doing so will give you a better understanding of how the code works.
You can also download the code files from the book’s companion website at http://www.wiley.com/go/ptl/androidprogramming.
Errata
I’ve tried to review and verify everything in the book as much as possible, but sometimes mistakes happen. It could be a typo in the text or the source code, but it could also be something that is missing or simply mistaken. I’ll update any errors in the sample code in the GitHub repository at https://github.com/ErikHellman/apptl with proper bug fixes.
Part I
Building a Better Foundation
Chapter 1 Fine-Tuning Your Development Environment
Chapter 2 Efficient Java Code for Android