CuuDuongThanCong.com CuuDuongThanCong.com Android Developer Tools Essentials Mike Wolfson CuuDuongThanCong.com Android Developer Tools Essentials by Mike Wolfson Copyright © 2013 Mike Wolfson All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://my.safaribooksonline.com) For more information, contact our corporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com Editors: Andy Oram and Rachel Roumeliotis Production Editor: Rachel Steely Copyeditor: Gillian McGarvey Proofreader: Charles Roumeliotis August 2013: Indexer: Ellen Troutman Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest First Edition Revision History for the First Edition: 2013-08-13: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449328214 for release details Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc Android Developer Tools Essentials, the image of a cassowary, and related trade dress are trade‐ marks of O’Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein ISBN: 978-1-449-32821-4 [LSI] CuuDuongThanCong.com Table of Contents Preface ix Getting Started Minimum Requirements Installing Java Installing the Android Software Development Kit Installing the ADT Bundle Developing Without Eclipse Command-Line Usage Using a Different IDE Configuring a Device for Development 3 6 Essential Tools 11 SDK Manager SDK Components Starting the SDK Manager Viewing Installed and Available Components ADT Preview Channel Android Debug Bridge (ADB) Starting ADB Querying for Device Instances Issuing Commands The Shell Command ADB Does a Lot More Resetting the ADB Server Additional Resources 11 11 12 13 15 17 17 18 19 20 22 23 24 Configuring Devices and Emulators 25 Using a Physical Device for Development 25 iii CuuDuongThanCong.com Capabilities and Limitations Configuring a Physical Device for Development Using an Emulator for Development Supported Features Android Virtual Devices Creating AVDs Emulator Options Advanced Emulator Configuration Using Hardware Acceleration Disabling the Boot Animation On Windows: Dedicating a Core to the Emulator 25 26 26 27 28 28 32 33 33 37 37 Using Devices and Emulators 39 Using the Emulator Starting the Emulator The Emulator Application The Devices Tool Keyboard Shortcuts File Explorer Developer Tools Application 39 40 47 48 50 50 52 Developing with Eclipse 55 Anatomy of the Eclipse Workspace Uncovering Additional Tools and Views Quick Button Code Templates Properties Editors XML Formatter The Android Key Quick Outline for XML Other Essential Eclipse Shortcuts Refactor Menu 55 57 59 59 65 67 67 68 69 70 Developing with Android Studio 71 Installing Android Studio Bundled SDK Default Project Location Anatomy of the Android Studio IDE Panels Toolbars Useful Actions in Android Studio Navigation iv CuuDuongThanCong.com | Table of Contents 71 72 74 74 74 75 76 76 The New Structure of an Android Project A Tour Around the New Structure Running and Debugging an Android Project Creating New Android Components Layout Designer and Layout Preview Layout Designer Layout Preview Generating an APK Interacting with Maven and Gradle Interacting with Maven Interacting with Gradle Version Control Integration Migrating from Eclipse Android Studio Tips and Tricks Refactoring and Code Generation Miscellaneous Shortcuts 77 77 78 79 80 80 81 82 83 83 84 85 86 86 87 87 Testing Your Code 89 Logcat Viewing the Logcat File Anatomy of a Log Message Filtering Based on Logging Level Using Tags to Filter Output Getting the Most Out of Logcat Viewing Alternative Log Buffers Predefined Output Formats Logcat Viewer in Eclipse Logcat Example Debugging Setting Your App to Debuggable Setting a Debug Point The Eclipse Debug Perspective Debugging Example Lint Command-Line Usage Running in Eclipse 89 89 89 91 92 92 93 93 93 94 98 99 99 100 101 107 108 110 Simulating Events 115 Simulating Location and Routes Simulating Telephony Operations Changing Networking Parameters Using a Device with Sensor Emulation 115 118 121 122 Table of Contents CuuDuongThanCong.com | v Advanced Sensor Testing Supported Sensors Simulating Sensor Events in Real Time Recording Sensor Scenarios Developer Options Menu 122 123 123 124 126 Build Tools 129 Compiling Your Code Packaging an APK for Release Signing Your App Building from the Command Line Using Ant Setting Up Your Project Building in Debug Mode Building an App to Release to the Play Store Additional Ant Commands Advanced Packaging Steps ProGuard Zipalign Gradle-Based Build Tools Installing Gradle Creating Multiple Build Variations Build File Build Tasks Generating a Gradle Build from Eclipse Using the Maven Tools 129 130 130 133 135 136 136 138 139 139 144 144 144 145 147 148 148 149 10 Monitoring System Resources 151 Memory Usage in Android Dalvik Debug Monitor Server (DDMS) Launching the DDMS Perspective Analyzer Tool Threads Heap Traceview Memory Analyzer Tool (MAT) Generating an HPROF File HPROF File Installing MAT into Eclipse Launching MAT from Within Eclipse Using MAT to Analyze HRPOF Files The MAT Overview Screen vi CuuDuongThanCong.com | Table of Contents 151 152 152 154 155 156 157 159 160 160 160 160 161 162 Viewing a Report 162 11 Working with the User Interface 165 Android Layout Basic Concepts Defining Layouts Using XML Views and ViewGroups Resources Leveraging ADT to Build Great UIs Editing XML Files Directly Using Templates Editing XML Directly Working with Graphics The Asset Tool Using Nine-Patch Images Asset Studio Website 165 165 167 170 171 172 172 173 182 183 185 187 12 Using the Graphical Editor 189 Generating Layouts Using the Graphical Layout Editor Palette Canvas Layout Actions Context-Sensitive Menu Outline View Properties Editor Configuration Chooser 189 191 192 194 194 196 196 197 13 Optimizing the User Interface 201 Introduction to UI Performance How Android Draws Views, and How It Affects UI Performance Hierarchy Viewer Starting the Hierarchy Viewer Loading the View Hierarchy into the Tools Navigating the Tree Hierarchy Gathering View Information Gathering View Rendering Details Example: Debugging a UI Using the Hierarchy Viewer Fixing Problems Using Lint Application Exerciser Monkey Grooming the Monkey Monkeyrunner Using Python to Create the Script Table of Contents CuuDuongThanCong.com 201 201 203 203 203 203 205 207 208 218 219 220 221 221 | vii Thanks for Reading! 222 Index 223 viii CuuDuongThanCong.com | Table of Contents $ adb shell monkey -p com.tools.demo 500 // activityResuming(com.tools.demo) // activityResuming(com.tools.demo) Events injected: 500 ## Network stats: elapsed time=36972ms (36972ms mobile, 0ms wifi, 0ms not connected) $ When you run this test, you can watch your device or emulator You will notice random elements of your UI being exercised as if an imaginary monkey were pressing on your app at random Grooming the Monkey There are a variety of ways to customize the Hierarchy Viewer’s test and report I will go through some of the most important ones in this section You can see a complete list of all options by typing: $ adb shell monkey help Letting the Monkey free The Monkey starts in the default application of the package you specified, and by default is contained within that package Any event that launches something external will be dropped This is generally a desired behavior, but there might be times when you want to be able to launch other packages This can be done by providing an additional package argument to the command: $ adb shell monkey -p com.foo.MyPackage -p com.foo.MyPackage2 500 Specifying event types and frequency It is possible to isolate the types of events that are triggered You can specify the per‐ centage of a particular event that should be run This is done with the event parameters So, for instance, if you want to ensure that 50 percent of the events are touch events (a down-up event in a single place on the screen), enter a command like: $ adb shell monkey pct-touch 50 -p com.foo.MyPackage 500 Verbosity level Depending on your needs, you may want to get back different levels of information from a test run It is possible to set the verbosity level to indicate how much information you wish to receive There are three possible levels, based on how many v’s you set Putting a single v (the default) provides the least information—basically just informa‐ tion about startup, test completion, and final results Putting vv will also output information during the test run Lastly, entering vvv provides the most information, including details about activities selected or not selected for testing 220 CuuDuongThanCong.com | Chapter 13: Optimizing the User Interface If that isn’t enough information for you, you can also include the hprof argument on the command line This will dump a large (~5MB) file that can be used by traceview (see Chapter 10) for memory profiling So to see the most verbose output, enter: $ adb shell monkey -vvv -hprof -p com.foo.MyPackage 500 Setting a seed value A seed value allows you to generate the same set of random events over and over This can be useful when you need to duplicate the same set of random events predictably to isolate a particular bug If you rerun the Monkey with the same seed number, the same exact events will be executed in the same sequence The seed can be any value, and determines where Monkey starts in its generation of pseudorandom events So we could choose the seed number 334422 as follows: $ adb shell monkey -seed 334422 -p com.foo.MyPackage 500 Monkeyrunner This tool (which despite the similar name to the tool we just discussed is completely different) is designed to control an Android device from outside of code, simulating how a real user would interact It provides an API so you can simulate user interactions by issuing commands through a script, or from the command line This is a powerful tool for simulating and running a consistent set of UI interactions in a repeatable fashion The monkeyrunner tool is a Java program that can be found with the rest of the tools in the ${android.home}/tools folder To run it, create a set of instructions you would like to simulate and feed to the tool This is a scripted application, so we need to give the tool a list of commands in order for it to run You can either type the commands one at a time in interactive mode or create a script to run a collection of commands together You can a lot with monkeyrunner, which provides a robust automated tooling plat‐ form This tool makes repeating a specific UI easy This makes it easy to standardize functional tests, which can be run across a variety of devices Using Python to Create the Script Rather than inventing a scripting language for this tool, the creators chose to use an existing language named Python Python was the logical choice because it is very pow‐ erful and popular It is a dynamic programming language that was designed to focus on creating clear, readable code that is modular and extensible Python combines functional and object-oriented programming concepts to make it easy to express procedural pro‐ grams It is beyond the scope of this book to explain the details of the Python language Monkeyrunner CuuDuongThanCong.com | 221 but we can step through a simple monkeyrunner script to show how it can be used Even if you don’t know Python, you should be able to follow along Let’s step through a simple example that shows how to install an application, launch an activity, take a screenshot of the menu options, and then store the screenshot for later review #menu_script.py # Import the monkeyrunner modules we need from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # Connect to a device device = MonkeyRunner.waitForConnection() # Install an application to the device device.installPackage(' /ToolsDemo.apk') # Run a component device.startActivity(component='com.tools.demo/.MainActivity') # Press and hold the 'MENU' button device.press('KEYCODE_MENU', MonkeyDevice.DOWN) # Take a screenshot screen1 = device.takeSnapshot() # Store the screenshot to the filesystem screen1.writeToFile('screens/menu_buttons.png','png') # Release the 'MENU' button device.press('KEYCODE_MENU', MonkeyDevice.UP) You can run this script by starting monkeyrunner from the command line with this script as a parameter: $ {android.home}\tools\monkeyrunner menu_script.py When you execute this command, you will be able to watch the actions you scripted on your device as they are happening Thanks for Reading! Well, that’s the end of this chapter on UI performance, and the end of the book With any technology that changes as rapidly as Android does, there will frequently be updates and new information There’s a website with pointers on that at http://www.mikewolf son.com And finally, I’d like to thank you for choosing this book and reading it all the way to the end In the final analysis, programmers don’t write books for fame or financial reward We write them to share our hard-won knowledge and make the path of other programmers a little bit easier I hope that this book fulfills that goal for you (and that you recommend it to all your developer friends!) 222 CuuDuongThanCong.com | Chapter 13: Optimizing the User Interface Index Symbols *:s, silencing all other log messages, 98 A accelerometer, SensorSimulator accelerometer example, 124 actions Android Actions, in Android Studio default toolbar, 75 common, in Android Studio, 76 Telephony Actions, Emulator Control tab, 118 activities Activity option in Configuration Chooser, 198 Don’t keep activities option, 126 log messages on, 90 Activity Manager, 22 ActivityManager:* tag, 93 ADB (Android Debug Bridge), 17–24 functionality, additional, 22 issuing commands, 19 managing applications on a device, 19 transferring files, 19 querying for device instances, 18 directing command to specific device, 18 finding connected devices, 18 resetting the server, 23 resources for learning more about, 24 shell command, 20–22 interactive mode, 20 one-off mode, 21 retrieving system data, 21 using Activity Manager, 22 starting, 17 ADB driver, downloading, adb logcat command, 97 ADB process, resetting from Devices tool, 50 ADT (Android Developer Tools), ix, ADT Preview Channel, 15 development process, x File Explorer, 50 Gradle integration, documentation on, 144 leveraging to build great UIs, 171 Lint, 107 requirements for, ix ADT Template Format Documentation, 65 ADT website, x Analyzer Tool, 153–155 running, 154 viewing results, 154 Android Attributes, getting information about, 106 android create avd command, 31 Android Debug Bridge (see ADB) Android Debug Monitor, 152 Android Developer Tools (see ADT) We’d like to hear your suggestions for improving our indexes Send email to index@oreilly.com 223 CuuDuongThanCong.com Android devices (see devices) Android Document website, Android key, 67 Android Manifest Editor, 65 tabs, 65 Android platforms SDK component, 12 selecting and downloading packages for, 14 Android Plugin for NetBeans, Android Software Development Kit (SDK) bundled with Android Studio, 72 components, 11 installing, 3–5 extracting tools to Android home, installing ADT Bundle, setting PATH variable, unzipping download artifact, Android Studio, 6, 71–88 anatomy of, 74 navigation, 76 panels, 74 status bar, 75 toolbars, 75 useful actions, 76 creating new Android components, 79 generating an APK, 82 installing, 72 bundled SDK, 72 default project location, 74 interacting with Gradle, 84 interacting with Maven, 83 Layout Designer, 80 Layout Preview, 81 migrating to, from Eclipse, 86 new structure for Android project, 77 refactoring and code generation, 87 running and debugging Android projects, 78 tips and tricks, 86 miscellaneous shortcuts, 87 refactoring and code generation short‐ cuts, 87 training resources, additional, 88 Version Control System (VCS) integrations, 85 android update project command, 135, 136 Android Virtual Devices (see AVDs) Ant, 129 building from command line with, 133–138 building app to release to Play Store, 136 224 CuuDuongThanCong.com | Index building in Debug mode, 136 more Ant commands, 138 setting up your project, 135 ant debug command, 136 ant release command, 137, 138 Apache Ant home page, 133 APKs (Android package files) generating in Android Studio, 82 packaging for release, 130–133 Asset Studio project, 187 Asset tool, 183–186 creating images, 184 selecting icon type, 184 AsyncTasks, monitoring with logcat, 95 attributes defined, 166 editing attribute values in XML files, 174 AVD Command Reference, 32 AVD Manager starting the emulator, 40 AVD launch options, 41 AVDs (Android Virtual Devices), 28 creating, 28 AVD Manager, 29 from command line, 31 location of AVD files, 31 emulator options, 32 setting up emulator using snapshots, 42 snapshots saved state, 45 starting the emulator from command line, 41 launch from snapshot, 46 B boot animation, disabling on emulator, 37, 42 breakpoints setting a debug point in source code, 99 setting debug points, 102 build file (Gradle), 147 build tools, 129–149 advanced packaging steps, 139–144 ProGuard, 139–144 Zipalign, 144 Android Studio interacting with Gradle, 84 Android Studio interacting with Maven, 83 building from command line using Ant, 133–138 additional Ant commands, 138 building app to release to Play Store, 136 building in Debug mode, 136 setting up your project, 135 compiling your code, 129 Gradle-based, 144–149 build file, 147 build tasks, 148 creating multiple build variations, 145 generating Gradle build from Eclipse, 148 installing Gradle, 144 Maven, 149 packaging APK for release, 130–133 signing your app, 130–133 build type (Gradle), 145 build variant (Gradle), 145 build.xml file (Ant), creating, 135 building Android apps from multiple source libraries, 135 steps in process, 134 C canvas (Graphical Layout editor), 192–196 context-sensitive menu, 194 layout actions, 194 certificates, 130 code completion, XML editor, 173 Code Editor (Eclipse), 56 code examples from this book, xi code generation and refactoring in Android Studio, 87 code templates, 60–65 accessing menu in Eclipse, 60 creating Master/detail flow, 60–65 code template confirmation, 62 Master/detail wizard, 61 viewing results, 63 creating your own, 64 XML editor, 172 command line building from, using Ant, 133–138 creating AVDs from, 31 draw9patch tool, 186 starting an emulator from, 41 using development tools from, using lint from, 108 excluding issues, 109 compiling your code, 129 Configuration Chooser, 197–200 Preview all screens, 199 setting screen resolution, 199 configuration parameters for AVDs, 30 context-sensitive menu, Graphical Layout edi‐ tor, 194 context-specific options in Android Studio, 86 convention over configuration, 145 Create AVD wizard, 29 custom content entered in log statement, 91 D Dalvik Compatible executables (DEX files), 129 Dalvik Debug Monitor Server (see DDMS) DDMS (Dalvik Debug Monitor Server), 152– 159 Analyzer Tool, 154–155 Heap tool, 156 launching DDMS perspective, 152 specifying location for emulator to simulate, 115 Threads tool, 155 Traceview tool, 158–159 DDMS perspective, 58 debug key, 130 Debug mode, 134 building in, using Ant, 136 Debug toolbar, Resume button, 104 Debug.dumpHprofData( ) method, 160 debuggable, setting app to, 99 debugging, 98–107 DDMS (Dalvik Debug Monitor Server), 152–159 Eclipse Debug Perspective, 100 enabled for testing apps on a phone, example, 101–107 setting debug points, 102 starting the debugger, 103 stepping through the code, 104–107 launched from Devices tool, 49 setting app to debuggable, 99 setting debug point, 99 validating on phone, dependencies defining project dependencies and target API, 135 listing tasks and dependencies in Gradle, 148 managing for packages selected in SDK Manager, 15 Developer Settings application, 126–127 Developer Tools application, 52 Index CuuDuongThanCong.com | 225 development tools (see tools) development, configuring a device for, Device Screen Capture (Devices tool), 50 devices configuring for development, querying for device instances in ADB, 18 directing command to specific device, 18 finding connected devices, 18 recording sensor interactions on physical de‐ vice, 125 using physical device for development, 25 capabilities and limitations, 25 configuring device for development, 26 devices command (ADB), 18 -s option, 18 Devices tool Devices tab, 48 operations launched from devices tab, 49 physical device shown in, 49 tracking emulators or devices hooked to your computer, 48 documentation Ant commands, 138 Gradle, 144 in Android SDK, 12 using alternative resources, 171 using NinePatchDrawables, 186 draw9patch command-line tool, 186 drawable documentation, 186 drivers, 12 Dump HPROF file button, 160 E Eclipse IDE, x, 3, 55–70 Android Key, 67 Android Studio and, 71 Build Automatically setting, 129 code templates, 60–65 DDMS perspective, launching, 115, 152 Debug Perspective, 100 developing without using, generating Gradle build from, 148 Initial Hierarchy View perspective, 203 launching, logcat viewer, 93 MAT, installing and launching, 160 moving to Android Studio from Eclipse, 86 other essential shortcuts, 69 226 CuuDuongThanCong.com | Index properties editors, 65 Android Manifest Editor, 65 quick outline for XML or Java class, 68–69 Refactor menu, 70 running Lint, 110 Java and XML editor integration, 112 Lint Options dialog, 112 Lint toolbar menu, 111 Quick Fix tool, 113 starting SDK Manager, 13 starting the emulator, 40 workspace layout, 55–59 Code Editor, 56 Outline, 56 Package Explorer, 56 Problems tab, 57 Quick button, 59 uncovering additional tools and views, 57–59 XML formatter, 67 Editor Preferences menu (XML editor), 181 Emulator Documentation, 50 emulators, 39 advanced configuration, 33 dedicating core to emulator on Windows, 37 disabling boot animation, 37 using hardware acceleration, 33–37 Android Virtual Devices (see AVDs) emulator application, 47 emulator options for AVDs, 32 keyboard shortcuts, 50 location simulation, 115–118 starting the emulator, 40–47 AVD launch options, 41 enabling options to launch from snap‐ shot, 46 from command line, 41 saving and retrieving a snapshot, 42 using AVD Manager, 40 using snapshots to improve performance, 42 tracking using Devices tool, 48 using for development, 26 supported and unsupported features, 27 events, simulating, 115–127 advanced sensor testing, 122–125 recording sensor scenarios, 124 SensorSimulator, supported sensors, 123 simulating sensor events in real time, 124 changing networking parameters, 121 location and routes, 115 telephony operations, 118–121 using Developer Settings application, 126– 127 using device with sensor emulation, 122 example code in Android SDK, 12 Export wizard, 131 F File Explorer, 50 files File Actions in Android Studio, 75 transferring between your computer and de‐ vices, 19 filtering applying multiple filter expressions to logcat command, 92 logcat output using custom tags, 98 logging output filter based on log tags, 92 logging output filter based on logging level, 91 flavor group (Gradle), 145 Force GPU Rendering option, 127 formatting monitoring with logcat, 95 XML files, using XML editor, 178 G garbage collection, 151 Google APIs (in Android SDK), 12 GPU rendering, forcing, 127 Gradle, 83, 129, 144–149 build file, 147 build tasks, 148 creating multiple build variations, 145 documentation, 144 generating Gradle build from Eclipse, 148 installing, 144 interacting with, using Android Studio, 84 key concepts and terms, 145 gradle command, 148 graphical editor, using, 189–200 canvas, 192–196 context-sensitive menu, 194 layout actions, 194 Configuration Chooser, 197–200 generating layouts with Graphical Layout editor, 189 Lint, 218 Outline view, 196 palette, 191 Properties editor, 196–197 graphics acceleration, starting emulator with, 42 graphics, working with, in Android UI, 183–187 Asset Studio website, 187 Asset tool, 183 using Nine-patch images, 186 H Hardware Accelerated Execution Manager (In‐ tel HAXM), 33–37 benefits and limitations of, 33 configuring an AVD, 34 downloading components, 34 installing software, 34 validating that it’s running, 36 hardware capabilities, Android phones, ix heap Heap tool, 153, 156 information displayed in sections, 157 inspecting with Devices tool, 50 Hierarchy Viewer, 203 example, debugging a UI using, 208–218 different ways to design a UI, 208 getting timing information with Tree View, 210 inspecting bad UI with Tree tool, 216 inspecting good UI with Tree tool, 217 reviewing structure with Tree Overview, 211 gathering view information, 205 identification and performance indica‐ tors, 206 measurement information, 206 gathering view rendering details, 207 loading view hierarchy into tools, 203 navigating tree hierarchy, 203 starting up, 203 Hierarchy Viewer perspective, 58 home directory, Android, HPROF file, 159 analyzing using MAT, 161 Index CuuDuongThanCong.com | 227 I IDEs (Integrated Development Environments), x, (see also Android Studio; Eclipse IDE) developing without using, Eclipse IDE or other IDE, using IDE other than Eclipse, install command (ADB), 19 J Java compiling your code, 129 Lint Quick Fix in, 114 Lint warnings in Java file, 112 signing APK with standard Java tools, 133 Java keystore, 131–133 JDK (Java Developer Kit), JRE (Java Runtime Environment), JSON parsing, monitoring with logcat, 95 JSON:* tag, 98 K keyboard shortcuts Android key, 67 Eclipse Quick Outline, 68 emulator, 50 in Android Studio, 76, 86 miscellaneous shortcuts in Android Studio, 87 navigating within XML files, 68 other Eclipse shortcuts, 69 Quick Fix feature in Eclipse, 113 refactoring and code generation in Android Studio, 87 setting breakpoints in code, 99 keystore checking or validating in Build wizard, 133 creating in Build wizard, 132 password information, storing in Ant, 137 selection, in Build wizard, 132 signing app with custom keystore, 137 L layout Android, basic concepts, 165 defining layouts using XML, 166 228 CuuDuongThanCong.com | Index defining layouts using XML/layout basics rendered, 168 leveraging ADT to build UIs, 171 resources, 170 Views and ViewGroups, 167 bad and good layouts for Android UI, 208 defined, 166 generating using Graphical Layout editor, 189–196 inserting new layouts into XML files, 173 nested layouts reducing performance, 202 two-pass layout process, 201 layout actions bar (Graphical Layout editor), 194 Layout Designer (Android Studio), 80 layout files, 166 Layout Preview (Android Studio), 81 Layout View (Hierarchy Viewer), 204 link suspects report (MAT), 162 Lint, 107 command-line usage, 108 disable command as permanent, 109 enable option, 109 excluding issues, 109 fixing UI performance problems, 218 listing issues currently enabled, using lint -list command, 107 running in Eclipse, 110 Java and XML editor integration, 112 Lint Options dialog, 112 Lint toolbar menu, 111 Quick Fix tool, 113 Linux Android Framework and, 20 Android home directory, keyboard shortcuts in Android Studio, 87, 87 minimum requirements for Android devel‐ opment, navigation shortcuts in Android Studio, 76 setting breakpoints, keyboard shortcut, 99 starting SDK Manager, 13 XML formatter, 67 localization, 198 locations, simulating, 115–118 log tags, 90 creating custom tags to represent logging categories, 95 using in multiple filters on logcat command, 93 using to filter output, 92 logcat, 89 filtering output based on logging level, 91 filtering output using log tags, 92 filtering verbose system logs to find needed information, 94–98 creating log statements, 95 determining areas to monitor, 95 filtering output, 98 verbose logging, 97 getting the most out of, 92 log messages, 89 logcat tool in Eclipse, 93 predefined output formats, 93 reading output, 90 viewing alternative log buffers, 93 viewing logcat file, 89 logging level, 90 example in testing of ActivityManager, 90 filtering based on, 91 M Mac OS X, x Android home directory, minimum requirements for Android devel‐ opment, navigation shortcuts in Android Studio, 76 setting breakpoints, keyboard shortcut, 99 starting SDK Manager, 13 XML formatter, 67 Manifest Editor, 65 tabs, 65 Master/detail flow, generating with code tem‐ plate, 60–65 MAT (Memory Analyzer Tool), 159–162 HPROF file, 160 installing into Eclipse, 160 launching from Eclipse, 160 Overview screen, 162 using to analyze HPROF files, 161 viewing a report, 162 MAT wizard, launching, 161 Maven, 129 interacting with, using Android Studio, 83 learning more about integration with An‐ droid, 149 memory Analyzer Tool, 153 usage in Android, 151 Memory Analyzer Tool (see MAT) memory leaks, 151 monitoring system resources (see system re‐ sources, monitoring) Monkey tool, 219 monkeyrunner, 221 N navigation shortcuts in Android Studio, 76 NetBeans IDE, network, monitoring with logcat, 95 NETWORK:* tag, 98 networking parameters, changing, simulation of, 121 Nine-Patch images, 186 Nurik, Roman, 65 O obfuscation of code, with Proguard, 89 Openintents.org, SensorSimulator project, 122 operating systems Android development on, x minimum hardware requirements for An‐ droid development, optimizing the UI (see UI, optimizing) orientation, 198 Outline view in Eclipse, 56 in graphical editor, 196 OutOfMemory exception, 151 Overview screen (MAT), 162 P Package Explorer (Eclipse), 56 packaging steps, advanced, 139–144 ProGuard, 139–144 Zipalign, 144 palette (Graphical Layout editor), 191 panels in Android Studio, 74 passwords Graphical editor, password example, 192 keystore for app built in Ant, 137 PATH environment variable, Index CuuDuongThanCong.com | 229 performance, UI, 201 (see also UI, performance) introduction to, 201–202 perspectives (Eclipse), 58 Pixel Perfect View, 58 Platform Tools, 12 Play Store building app in Ant to release to Play Store, 136 packaging an APK for release on, 130–133 Pointer Location, 126 port forwarding, 122 PowerManagerService:E tag, 93 Problems tab (Eclipse), 57 process ID of application originating log mes‐ sage, 90 product flavor (Gradle), 145 Profile panel (Traceview), 159 ProGuard tool, 89, 139–144 configuring, 140–142 enabling, 139 viewing obfuscated code, 142 project files, Android Studio, default location, 74 project.properties file, 135 projects new file structure in Android Studio, 77 running and debugging in Android Studio, 78 properties editors, 65 Android Manifest Editor, 65 Properties editor in Graphical Layout editor, 196–197 push and pull commands (ADT), 19 Python, using to create monkeyrunner script, 222 Q Quick button (Eclipse), 59 Quick Fix tool, Lint running in Eclipse, 113 Quick Outline for XML, 68 in Java class, 69 R Refactor menu, 70 Extract Style, 70 renaming item IDs, 70 230 CuuDuongThanCong.com | Index refactoring in Android Studio, 87 Refactor menu of XML editor, 176 Release mode, 134 building in, using Ant, 136 Reset ADB (Devices tool), 50 resource files, 170 resource qualifiers, 167 modifying each independently, 200 resources, 151, 170 (see also system resources, monitoring) resource limitations for mobile apps, x S sample code in Android SDK, 12 scale factor (AVD launch option), 41 scenarios, recording sensor scenarios, 124 screen resolutions setting in visual editor, 199 supporting multiple, 170 screens controlling screen size in visual editor, 198 multiple screen sizes for Android devices, ix Preview All Screens in graphical editor, 199 Show screen updates, Developer Options menu, 126 SDK Manager, 11–17 ADT Preview Channel, 15 enabling, 15 installing Preview Tools, 16 reverting to released tools, 17 starting, 12 viewing installed and available components, 14 deleting and updating components, 15 installing packages, 14 managing dependencies, 15 selecting packages, 14 SDK option, Configuration Chooser, 198 SDK Tools, 12 SdkControllerSensor app, 122 secure.properties file, 137 self-signed certificates, 130 sensor emulation, using device with, 122 SensorRecordFromDevice.apk, 125 SensorSimulator, 122 accelerometer example, 124 recording sensor scenarios, 124 supported sensors, 123 Settings app Developer Options, 126 enabling developer options, 52 USB Debugging, 7, 26 shell interface (ADB), 20–22 interactive mode, 20 one-off mode, 21 retrieving system data, 21 using Activity Manager, 22 Show screen updates, 126 signing apps, 130–133 simulating events (see events, simulating) SMS messaging, simulating, 118–121 snapshots AVD launch option, 41 AVD snapshots saved state, 45 using to improve emulator performance, 42 saving and retrieving a snapshot, 42 Software Development Kit (see Android Soft‐ ware Development Kit; entries beginning with SDK) Sonatype, resources on Maven, 149 sourceset (Gradle), 145 stacktrace, 155 related to a single thread, 156 Strict Mode Enabled, 126 styles defined, 166 Extract Style in Refactor menu, 70 syncing Gradle files with Android app, 85 system data, retrieving with ADB shell com‐ mand, 21 system resources, monitoring, 151–162 DDMS (Dalvik Debug Monitor Server), 152–159 MAT (Memory Analyzer Tool), 159–162 memory usage in Android, 151 T tasks (Gradle), 145, 148 telephony operations, simulating, 118–121 testing code, 89–114 debugging, 98–107 Eclipse Debug Perspective, 100 example, 101–107 setting app to debuggable, 99 setting debug point, 99 filtering logging output based on logging level, 91 filtering logging output on log tags, 92 getting the most out of logcat, 92 log messages, 89 logcat example, 94–98 creating log statements, 95 determining areas to monitor, 95 filtering logcat output, 98 verbose logging with logcat, 97 predefined output formats for log messages, 93 reading logcat output, 90 using Lint, 107 command-line usage, 108 running Lint in Eclipse, 110 using logcat viewer in Eclipse, 93 viewing alternative log buffers, 93 viewing logcat files, 89 themes, 166 Theme option in Configuration Chooser, 198 third-party add-ons, 12 Threads tool, 153, 155 running, 155 viewing thread information, 156 Timeline panel (Traceview), 158 toolbars in Android Studio, 75 tools displaying additional tools in Eclipse, 57 essential, 11 ADB (Android Debug Bridge), 17–24 SDK Manager, 11–17 Traceview tool, 153, 158–159 output, Timeline panel, 158 Profile panel, 159 training resources for Android Studio, 88 Tree Overview (Hierarchy Viewer), 204 U UI (user interface), 165–187 Android layout, basic concepts, 165 defining layouts with XML, 166 leveraging ADT to build UIs, 171 resources, 170 Views and ViewGroups, 167 designing using Graphical Layout tools, 189–200 editing XML files directly, 172–183 monitoring with logcat, 95 Index CuuDuongThanCong.com | 231 optimizing, 201–222 application exerciser Monkey, 219 debugging UI with Hierarchy Viewer, 208–218 fixing problems using Lint, 218 Hierarchy Viewer, 203–208 UI performance, 201–202 using monkeyrunner, 221 working with graphics, 183–187 Asset Studio, 187 Asset tool, 183–186 using Nine-patch images, 186 UI Thread, 155 UI:* tag, 93, 98 uninstall command (ADB), 20 USB Debugging enabling on Android phone, enabling on physical device, 26 USB drivers, 12 V Version Control System (VCS) integrations with Android Studio, 85 ViewGroups, 167 views adding to Eclipse layout, 58 drawing of Views and its effect on UI perfor‐ mance, 201 Views base class, Android layouts, 167 W web page for this book, xii widgets, 166 inserting into XML files, 173 Windows Android home directory, 232 CuuDuongThanCong.com | Index connecting Android-powered device for testing with ADB driver, dedicating a core to the emulator, 37 keyboard shortcuts in Android Studio, 87 minimum requirements for Android devel‐ opment, navigation shortcuts in Android Studio, 76 setting breakpoints, keyboard shortcut, 99 starting SDK Manager, 12 Windows 64-bit OS, x XML formatter, 67 X XML automatically created by Android Studio Layout Designer, 81 defining Android layouts, 166 editing XML files directly, 172–183 code completion, 173 editor preferences, 181 formatting, 178 inserting new layouts or widgets, 173 Refactor menu of XML editor, 176 using templates, 172 formatter, 67 layout editor in Android Studio Layout Pre‐ view, 81 Lint Quick Fix in, 113 Lint warnings in XML file, 112 quick outline for, 68 XML files editing directly attribute values, 174 Z Zipalign, 144 About the Author Mike Wolfson is a passionate mobile designer/developer working out of Phoenix, AZ He has been in the software field for almost 20 years, and with Android since its intro‐ duction Currently, he develops Android applications for the health care field He has written a variety of successful apps, and is best known for the “Droid Of The Day” App Mike has spent his career helping others learn technology He currently runs the local Google Developer Group, and has been a lifelong supporter of a variety of other group learning activities He has spoken about Android and mobile development at a variety of conferences and user groups When he is not geeking out about phones, he enjoys the outdoors (snowboarding, hik‐ ing, scuba diving), collecting PEZ dispensers, and chasing his young (but quick) daughter Colophon The animal on the cover of Android Developer Tools Essentials is a cassowary (genus Casuarius), a large, flightless bird that is native to the rainforests of New Guinea and Australia This genus consists of three species: one is extinct and the rest are living but endangered It is estimated that only 1,500 cassowaries exist in the entirety of Australia Like the ostrich and the emu, the cassowary is a ratite, or flightless bird Although the three species of cassowary differ slightly in size, the Southern cassowary is the largest, with females reaching heights of six and a half feet Despite their enormous size, cas‐ sowaries subsist mainly on fruits that have fallen from trees and will occasionally eat fungus or insects if necessary They swallow their food whole, sometimes taking in entire bananas or mangos in one gulp All species of cassowary are black with bright blue and red necks and hard outgrowths of flesh on the tops of their heads called casques There is much debate about what purpose the casques serve, with theories ranging from protection from falling fruit to an amplifier of the birds’ rumbling calls It is also possible that they allow the bird to forge ahead through dense forest growth, with the casque acting as a battering ram to clear foliage out of the way The thick feathers that adorn the bird’s body are also thought to provide protection from the undergrowth given their unique two-quilled design Female cassowaries are much larger than males and are in charge of initiating breeding and courtship After a female selects a mate, they court for almost a month before breeding The female will create a nest and lay the eggs, then immediately start off to find another mate The father then incubates the eggs until they hatch by sitting on them for fifty days Baby cassowaries are born with tan and white stripes to help them blend in with the detritus on the rainforest floor The chicks follow their father around for about ten months and learn how to forage fruit and insects Eventually, the father chases CuuDuongThanCong.com the chicks away so that they can start life on their own and he can breed with another female Cassowaries are extremely territorial, so in the wild they are solitary creatures Generally they are shy around humans, opting to run away rather than be noticed However, cassowaries can be very dangerous to people and other animals if provoked Given the rate at which human civilization is encroaching upon cassowary habitats, run-ins with these giant birds are becoming more and more common In 2003, 150 attacks involving humans were reported, and 75% of these came from instances of people trying to feed the birds The cassowary’s best defense is its dagger-like claws, one on each center toe, which can grow to be four inches long One kick from a cassowary’s powerful legs can slice open all but the toughest hides Especially in northern Australia, where roads bisect the rainforests, encounters with cassowaries are on the rise Although large swaths of land are now protected, the future of the cassowary is as unclear as that of the rainforest; both must contend with human development and the environmental effects of global warming The cover image is from the Dover Pictorial Archive The cover font is Adobe ITC Garamond The text font is Adobe Minion Pro; the heading font is Adobe Myriad Con‐ densed; and the code font is Dalton Maag’s Ubuntu Mono CuuDuongThanCong.com ...CuuDuongThanCong.com Android Developer Tools Essentials Mike Wolfson CuuDuongThanCong.com Android Developer Tools Essentials by Mike Wolfson Copyright © 2013 Mike Wolfson All rights reserved... includes the title, author, publisher, and ISBN For example: ? ?Android Developer Tools Essentials by Mike Wolfson (O’Reilly) Copyright 2013 Mike Wolfson, 978-1-449-32821-4.” Supplemental material (code... Install the Android SDK Install the Eclipse Integrated Development Environment (IDE) Install the Android Developer Tools (ADT) plug-in for Eclipse Minimum Requirements To develop for Android, you’ll