Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Android High Performance Programming
Android High Performance Programming

Android High Performance Programming: Build fast and efficient Android apps that run as reliably as clockwork in a multi-device world

Arrow left icon
Profile Icon López Mañas Profile Icon Grancini
Arrow right icon
$19.99 per month
Paperback Aug 2016 412 pages 1st Edition
eBook
€28.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon López Mañas Profile Icon Grancini
Arrow right icon
$19.99 per month
Paperback Aug 2016 412 pages 1st Edition
eBook
€28.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
€28.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Android High Performance Programming

Chapter 2. Efficient Debugging

Every developer becomes familiar with the word "bug" early on, and the relationship will last for their entire professional career. A bug is an error or flaw in a software system that provokes an unexpected and incorrect result.

There is some discussion about the etymology of the word. It was originally intended to describe technical malfunctions in hardware systems and the first reference to its usage comes from Thomas Edison. Grace Hopper, a computer pioneer, apparently traced in 1946 the malfunctioning of the computer Mark II to a moth that was trapped inside the relay. This physical bug ended up representing not only physical bugs trapped inside machines and causing malfunctions, but also logical bugs or software errors.

Debugging is, in this context, the process of finding bugs or malfunctions in a software system. Debugging involves numerous factors, including reading logs, memory dumping and analysis, profiling, and system monitoring...

Android Debug Bridge

Android Debug Bridge, more widely known as ADB, is a core tool for Android. It is included in the Android SDK, in the folder/platform tools. If you go to this folder and call the command adb, you will see on the screen a list of the available options.

Tip

If you haven't done this by now, this is a productivity tip that will pay off in probably the first minute working with ADB. Add to your PATH environmental variable the location where you have stored your Android SDK. From this moment, you will be able to call all the tools included within that folder from any part of your system.

With adb, we can perform multiple operations, including displaying devices, taking screenshots, or connecting to and disconnecting from different devices. It is not the purpose of this book to give a thorough review of each operation of a tool, but here, we present a list of the most common and useful functionalities of adb:

#

Command

Description

1

adb logcat *:E|D|I

Starts logcat...

Dalvik Debug Monitor Server

Dalvik Debug Monitor Server is also known as DDMS. This utility runs on top of adb, and provides a graphical interface with a big set of functionalities, including thread and heap information, logcat, SMS/call simulation, location data, and more. This is how DDMS looks when it starts:

Dalvik Debug Monitor Server

The screen has different sections:

  1. The top-left section shows the active devices and the different processes running on the device.
  2. The top-right section shows a variety of options, the default option being the file explorer. At the bottom, LogCat is shown.

There are more available options in the DDMS, so let's explore them in detail. First, the section we saw on the top-left side:

  1. The Dalvik Debug Monitor Server icon starts debugging the selected process.
  2. The Dalvik Debug Monitor Server icon will update the heap every time the GC is triggered for the selected process (more information on this later).
  3. The next icon, Dalvik Debug Monitor Server, dumps HPROF in a file. HPROF is a binary format that contains the snapshot of an application heap. There are some...

Capturing and analyzing thread information

Now we want to see how we can deal with thread debugging. The traditional approach of setting breakpoints and waiting until a thread is called will not work well here, since a multithreaded application might have several threads running at the same time and independently of each other. Hence, we want to visualize and access them independently.

Select a process on the left-hand side of the list and click the Capturing and analyzing thread information icon. If now you click in the threads section on the right-hand side, you will see how this section has been updated with information regarding the threads of the current process:

Capturing and analyzing thread information

Note

Some developers are confused about what processes and threads are, so just in case: a process provides the required resources to execute a program (virtual address space, executable code, security context, and so on). A process is the instance of execution of a process (also referred to as a task in some contexts). Several processes can be associated with the same...

Heap analysis and visualization

We have learned how to debug threads using DDMS. Now we will learn how to properly analyze the memory heap of an application: that is, the portion of memory where the allocated memory resides. This is very important when it comes to debugging memory leaks.

Let's use a heap dump to track down the problem. Click the Heap analysis and visualization icon to dump the HPROF file and choose where you want to save the file. Now run hprof-conv over the file. hprof-conv is an Android utility that converts the .hprof file from the Dalvik format to the J2SE HPROF format, so it can be opened with standard tools. It can be found under /platform-tools. To run it, you need to type the following:

hprof-conv dump.hprof converted-dump.hprof

Now you will have a file that can be understood by some standard tools. In order to read the file, we will use MAT, a standalone version downloadable from http://www.eclipse.org/mat/downloads.php.

MAT is a very complex and powerful tool. Click on File and open Heap...

Allocation tracker

The allocation tracker is a tool provided by Android that records an app's memory allocations and lists all allocated objects for the profiling cycle with their call stack, size, and allocating code. This goes further than the memory heap and allows us to identify individual pieces of memory being created. It is good to identify places in the code that might be allocating memory inefficiently and to identify objects of the same type that are being allocated and deallocated over a short period of time.

To start using the allocation tracker tool, select your process on the left-hand side, select the Allocation Tracker section in the pane on the right, and then click on the Stop Tracking button. A similar window to the following one will open:

Allocation tracker

The amount of information can be overwhelming, and there is, therefore, a filter at the bottom where you can specify which information you want to get. If you click on one of the rows, the location of the allocated object will be...

Android Debug Bridge


Android Debug Bridge, more widely known as ADB, is a core tool for Android. It is included in the Android SDK, in the folder/platform tools. If you go to this folder and call the command adb, you will see on the screen a list of the available options.

Tip

If you haven't done this by now, this is a productivity tip that will pay off in probably the first minute working with ADB. Add to your PATH environmental variable the location where you have stored your Android SDK. From this moment, you will be able to call all the tools included within that folder from any part of your system.

With adb, we can perform multiple operations, including displaying devices, taking screenshots, or connecting to and disconnecting from different devices. It is not the purpose of this book to give a thorough review of each operation of a tool, but here, we present a list of the most common and useful functionalities of adb:

#

Command

Description

1

adb logcat *:E|D|I

Starts logcat in...

Dalvik Debug Monitor Server


Dalvik Debug Monitor Server is also known as DDMS. This utility runs on top of adb, and provides a graphical interface with a big set of functionalities, including thread and heap information, logcat, SMS/call simulation, location data, and more. This is how DDMS looks when it starts:

The screen has different sections:

  1. The top-left section shows the active devices and the different processes running on the device.

  2. The top-right section shows a variety of options, the default option being the file explorer. At the bottom, LogCat is shown.

There are more available options in the DDMS, so let's explore them in detail. First, the section we saw on the top-left side:

  1. The icon starts debugging the selected process.
  2. The icon will update the heap every time the GC is triggered for the selected process (more information on this later).
  3. The next icon, , dumps HPROF in a file. HPROF is a binary format that contains the snapshot of an application heap. There are some tools...

Capturing and analyzing thread information


Now we want to see how we can deal with thread debugging. The traditional approach of setting breakpoints and waiting until a thread is called will not work well here, since a multithreaded application might have several threads running at the same time and independently of each other. Hence, we want to visualize and access them independently.

Select a process on the left-hand side of the list and click the icon. If now you click in the threads section on the right-hand side, you will see how this section has been updated with information regarding the threads of the current process:

Note

Some developers are confused about what processes and threads are, so just in case: a process provides the required resources to execute a program (virtual address space, executable code, security context, and so on). A process is the instance of execution of a process (also referred to as a task in some contexts). Several processes can be associated with the same...

Heap analysis and visualization


We have learned how to debug threads using DDMS. Now we will learn how to properly analyze the memory heap of an application: that is, the portion of memory where the allocated memory resides. This is very important when it comes to debugging memory leaks.

Let's use a heap dump to track down the problem. Click the icon to dump the HPROF file and choose where you want to save the file. Now run hprof-conv over the file. hprof-conv is an Android utility that converts the .hprof file from the Dalvik format to the J2SE HPROF format, so it can be opened with standard tools. It can be found under /platform-tools. To run it, you need to type the following:

hprof-conv dump.hprof converted-dump.hprof

Now you will have a file that can be understood by some standard tools. In order to read the file, we will use MAT, a standalone version downloadable from http://www.eclipse.org/mat/downloads.php.

MAT is a very complex and powerful tool. Click on File and open Heap Dump...

Allocation tracker


The allocation tracker is a tool provided by Android that records an app's memory allocations and lists all allocated objects for the profiling cycle with their call stack, size, and allocating code. This goes further than the memory heap and allows us to identify individual pieces of memory being created. It is good to identify places in the code that might be allocating memory inefficiently and to identify objects of the same type that are being allocated and deallocated over a short period of time.

To start using the allocation tracker tool, select your process on the left-hand side, select the Allocation Tracker section in the pane on the right, and then click on the Stop Tracking button. A similar window to the following one will open:

The amount of information can be overwhelming, and there is, therefore, a filter at the bottom where you can specify which information you want to get. If you click on one of the rows, the location of the allocated object will be printed...

Network usage


In Android 4.0, the Data Usage feature in Settings enables long-term monitoring of how an application uses network resources. Starting with Android 4.0.3, it is possible to monitor an application using network resources in real time. It is possible as well to distinguish traffic sources by applying a tag to network sockets before use.

To display the network usage of an application, select a process from the left-hand side. Then move to the Network Statistics tab and click on the Start button. You can select the tracking speed: every 100, 250, or 500 ms. Then, interact with your application. A similar screen to the following one will be displayed:

The bottom of the screen displays the network information by Tag, and collected by Total. It is possible to see the number of bytes and packages being sent and received in total, as well as a graphical representation of them.

If you haven't done it yet, it is a good idea to set tags on a per-thread basis with the help of the TrafficStats...

Emulator Control


The last tab in the DDMS is the so-called Emulator Control. By selecting one of our adb devices and starting it, a tab with some additional options will be shown:

With the emulator control, we can modify our phone network in several ways:

  • It is possible to select a different configuration for the data and voice (home network, roaming, not found, denied, and so on)

  • The speed and latency of the Internet connection can be defined

  • It is possible to simulate an incoming phone call or an incoming SMS from a defined phone number

  • We can send fake locations to our emulator. This can be done either manually or by uploading a GPX/KML file

System status


The last section of the DDMS is the System Information tab. Here, it is possible to find out up to three different information categories: the CPU load, memory usage at the current time, and the frame render time (this one is especially important when benchmarking and debugging video games):

Debugging the UI


We have focused until now on memory, threading, and the system aspects of Android. There is a more visual aspect that can also dramatically improve the performance of our application: the user interface (UI). Android provides a tool called Hierarchy Viewer to debug and optimize any UI designed for Android. Hierarchy Viewer provides a visual representation of the hierarchy of layouts of an application with information about the performance of each node that can be found on the layout. It provides a so-called Pixel Perfect window with magnified information of the display, in case a close look at pixels is required.

To run Hierarchy Viewer, we need first to connect our device or emulator. Note that, for security reasons, only devices running a developer version of the Android system will work with Hierarchy Viewer. When it has been connected, launch the hierarchyviewer program from the /tools directory. If you have not yet set up this directory as part of your system PATH, this...

Profiling with Hierarchy Viewer


Hierarchy Viewer provides a powerful profiler to analyze and optimize the application. To proceed with the profiling, click the icon, Profile Node. If the hierarchy of your view is quite large, it might take some time until it is initialized.

At this point, all the views in your hierarchy will get three dots:

  • The left dot represents the Draw process of the rendering pipeline

  • The middle dot represents the Layout phase

  • The right dot represents the Execute phase

Each dot color within a view has a different meaning:

  • A green dot means that the view is rendering faster than at least half of the other views. Generally, a green color can be seen as a high-performing view.

  • A yellow dot means that the view is rendering faster than the bottom half of the views in the hierarchy. This is only relative, but yellow colors might require us to take a look at the view.

  • Red means the view is among the slowest half of views. Generally, we want to take a look at these values.

How can...

Systrace


Systrace is a tool included in the Google SDK to analyze the performance of an application. It captures and displays the execution time from your application on the kernel level (capturing information such as CPU scheduler, application threads, and disk activity). After the analysis has been completed, it generates an HTML file with all the information compiled.

To make it work, click the Systrace button in the DDMS view (). A screen such as the following will appear:

On this screen, we can input a few parameters for Systrace:

  • Destination where the file will be stored as an HTML file.

  • Trace duration: the default value is 5 seconds. 30 seconds is a good value to cope with a good amount of information.

  • Trace buffer size: how big the buffer should be for tracing.

  • We can select the process from which we will enable the application traces, so normally we will select our own application here.

  • We need to select some of the tags that we would like to interact with from the list.

When everything...

Android device debug options


When we are debugging an Android device, we need to activate developer mode. This mode is hidden by default, and we need to activate it manually if we need to connect the device to ADB or to use some of its options. Android's creators did a good job at hiding this option.

Let's see how we can activate this option to have a better understanding of Android debugging, and how can we play with the different debug configurations.

As mentioned, the developer options in the device are really hidden by default. The purpose for this is very likely to make it only available to advanced users and not to normal users. A casual person will not need to access the features in this section; doing so might options that could harm the device.

In standard ROMs we need to go to the About section, scroll down until we see the Build number entry, and then tap five times in quick succession. A small dialog will be displayed saying that we are now a developer:

Due to custom ROM customization...

Android Instant Run


At the time of writing, Google released Android Studio 2.2 Preview. This is (as the name suggests) the second major version of Android Studio, and it comes with many fixes, performance improvements, and an awesome tool called Android Instant Run. This tool allows us to perform changes in the code and display them instantly in our device or emulator. This is a priceless feature when we are debugging, since we do not need to recompile the application, start it again, and reconnect it to adb.

To activate this option, we need to go to Preferences, then look for Build, Execution, Deployment | Instant Run. Check Enable Instant Run to hot swap code/resource changes on deploy (default enabled); if you are running the right version of the Gradle plugin, you will be able to activate it:

To run an application, select Run so Android Studio operates normally. Now comes the interesting part: after you have performed edits or modifications on your source code, clicking Run once more will...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Wide coverage of various topics that help in developing optimal applications
  • Explore the concepts of Advanced Native Coding in depth
  • A must-have for professional-standard Android developers for whom performance failures and the sloppy use of resources are simply unacceptable

Description

Performant applications are one of the key drivers of success in the mobile world. Users may abandon an app if it runs slowly. Learning how to build applications that balance speed and performance with functionality and UX can be a challenge; however, it's now more important than ever to get that balance right. Android High Performance will start you thinking about how to wring the most from any hardware your app is installed on, so you can increase your reach and engagement. The book begins by providing an introduction to state–of-the-art Android techniques and the importance of performance in an Android application. Then, we will explain the Android SDK tools regularly used to debug and profile Android applications. We will also learn about some advanced topics such as building layouts, multithreading, networking, and security. Battery life is one of the biggest bottlenecks in applications; and this book will show typical examples of code that exhausts battery life, how to prevent this, and how to measure battery consumption from an application in every kind of situation to ensure your apps don’t drain more than they should. This book explains techniques for building optimized and efficient systems that do not drain the battery, cause memory leaks, or slow down with time.

Who is this book for?

This book is aimed at developers with an advanced knowledge of Android and who want to test their skills and learn new techniques to increase the performance of their applications. We assume they are comfortable working with the entire Android SDK, and have been doing it for a few years. They need to be familiar with frameworks such as NDK to use native code, which is crucial for app performance

What you will learn

  • Create Android applications that squeeze the most from the limited resource capacity of devices
  • Swap code that isn't performing
  • Efficient memory management by identifying problems such as leaks
  • Reap the benefits of multithreaded and asynchronous programming
  • Maximize the security and encryption mechanisms natively provided by Android
  • Perform efficient network operations and techniques to retrieve data from servers
  • Master the NDK to write native code that can perform faster operations

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 29, 2016
Length: 412 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288951
Vendor :
Google
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 29, 2016
Length: 412 pages
Edition : 1st
Language : English
ISBN-13 : 9781785288951
Vendor :
Google
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
Android Application Development Cookbook
€36.99
Android High Performance Programming
€41.99
Asynchronous Android Programming
€41.99
Total 120.97 Stars icon

Table of Contents

11 Chapters
1. Introduction: Why High Performance? Chevron down icon Chevron up icon
2. Efficient Debugging Chevron down icon Chevron up icon
3. Building Layouts Chevron down icon Chevron up icon
4. Memory Chevron down icon Chevron up icon
5. Multithreading Chevron down icon Chevron up icon
6. Networking Chevron down icon Chevron up icon
7. Security Chevron down icon Chevron up icon
8. Optimizing Battery Consumption Chevron down icon Chevron up icon
9. Native Coding in Android Chevron down icon Chevron up icon
10. Performance Tips Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.