Home Android & Kotlin Books Real-World Android by Tutorials

Advanced Debugging Written by Subhrajyoti Sen

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

When you develop mobile apps, you’ll often have issues that are hard to debug. The app might be might very slow for some users or drain too much battery for others. Or you might find that the UI is a bit laggy or doesn’t quite match the design mock-ups. Debugging these issues can be tedious. Fortunately, there are tools that make the process easier.

In this chapter, you’ll learn about:

  • Finding and fixing memory leaks using LeakCanary.
  • Using the Memory Profiler to find Fragment and Activity leaks.
  • Examining network calls using the Network Profiler.
  • Finding Wake Locks using the Energy Profiler.
  • Using Layout Inspector to improve your layouts.

You’ll start by looking at memory leaks.

Memory leaks

In Java-based environments, the garbage collector frees up memory allocated to objects that are no longer used and are eligible for collection. An object is eligible for collection when no active process references it. Sometimes, however, a process keeps a reference to objects you don’t need anymore, causing a memory leak. Android apps have limited memory, so leaks can cause OutOfMemoryError exceptions.

Therefore, it’s essential to find and fix memory leaks early, before they degrade your app’s performance. LeakCanary is a library that simplifies memory leak detection in your app. It works by creating a dump of the heap memory and parsing it to find the source of the leak.

Installing LeakCanary

To install LeakCanary, add the following dependency to your app build.gradle:

debugImplementation "com.squareup.leakcanary:leakcanary-android:2.4"

Adding obfuscation support

Since you enabled Proguard on the debug build variant, LeakCanary needs some extra setup. You can skip this setup if you disable Proguard for debugging.

classpath "com.squareup.leakcanary:leakcanary-deobfuscation-gradle-plugin:2.4"
apply plugin: 'com.squareup.leakcanary.deobfuscation'
leakCanary {
  filterObfuscatedVariants { variant ->
    variant.name == "debug"

Detecting memory leaks

There’s no secret map that can help you find memory leaks. In your regular development workflow, you won’t look for memory leaks explicitly. Instead, you just install LeakCanary and continue to develop your app as normal. If there is a leak, LeakCanary will notify you by adding a notification to the system notification tray.

Figure 21.1 — LeakCanary Memory Leak Notification
Mupoya 88.8 — HaujYedabv Mukujn Koeq Layusifotueh

Finding the leak source

In this section, you’ll use the heap dump to find the source of the leak.

Figure 21.2 — The Leaks App
Mexuna 35.4 — Pve Rooyx Adb

Figure 21.3 — LeakCanary Leak List
Xufuwu 30.7 — FoirLenawm Doih Culs

Figure 21.4 — Leak Information Details
Pugale 22.1 — Jouk Ucyegnuviaf Gozoajj

Figure 21.5 — Leak Sources
Rogaya 31.1 — Zooy Kaapyeg

Understanding the leak cause

You now know some important information: The fling animation is causing a memory leak via the FloatingActionButton named call. It’s time to figure out why.

Plugging the leak

To fix this leak, you have to make sure that AnimalDetailsFragment doesn’t contain any global variables that hold a reference to a view.

private val callScaleXSpringAnimation = SpringAnimation(binding.call, DynamicAnimation.SCALE_X).apply {
  spring = springForce

private val callScaleYSpringAnimation = SpringAnimation(binding.call, DynamicAnimation.SCALE_Y).apply {
  spring = springForce

private val callFlingXAnimation = FlingAnimation(binding.call, DynamicAnimation.X).apply {
  friction = FLING_FRICTION
  setMaxValue(binding.root.width.toFloat() - binding.call.width.toFloat())

private val callFlingYAnimation = FlingAnimation(binding.call, DynamicAnimation.Y).apply {
  friction = FLING_FRICTION
  setMaxValue(binding.root.height.toFloat() - binding.call.width.toFloat())

Android Studio Profiler

In recent versions of Android Studio, Google has significantly improved the tools you can use to debug complicated issues, especially the Profiler.

Figure 21.6 — Android Studio Profiler
Vufixa 65.9 — Ovgduuw Hquqio Yzovolog

Finding memory leaks with the Memory Profiler

In addition to using LeakCanary, you can also use Android Studio’s Profiler to detect memory leaks. Android Studio 3.6 added support for automatic detection of Activity and Fragment leaks. In this section, you’ll introduce a memory leak in the codebase that leaks a Fragment. You’ll then use the Memory Profiler to find and trace the leak.

Introducing a Fragment leak

Open MainActivity.kt and add the following global variable before onCreate():

lateinit var currentFragment: Fragment
(requireActivity() as MainActivity).currentFragment = this

Detecting and tracing the leak

Build and run. Once the app is running on a device, open the Profiler tab and start a session. Select the MEMORY row. You will see a screen like the one below:

Figure 21.7 — Memory Profiler
Gijofe 78.1 — Nakiwt Qkawisej

Figure 21.8 — Memory Profiler Heap Dump
Qiyure 65.8 — Demahp Pgohayet Qiax Zozv

Figure 21.9 — Example of Memory Leak in the Memory Profiler
Dofiki 52.4 — Eduxsqo ur Fovacg Poip uq gni Vadofp Vqutofec

Figure 21.10 — Memory Profile Leak Instance List
Herina 26.44 — Yujozz Slodiqi Xoow Ovgjanse Haxd

Figure 21.11 — Memory Profile Leaks References
Qohuya 52.29 — Zexexd Hlikopi Raejd Binaxehwuw

Network Profiler

Up until now, you’ve probably used HttpLoggingInterceptor to analyze your network calls by logging the network requests and their responses. This approach works fine if you’re interested in individual calls and just want to verify that they take place.

Why network profiling matters

You might think you’ll only use the Network Profiler to find details of network calls when integrating new features or APIs, but Network Profiler can do much more.

Navigating the Network Profiler

Build and run. Go to the Profiler tab in Android Studio and click anywhere in the NETWORK timeline. This opens the Network Profiler.

Figure 21.12 — Android Studio Network Profiler
Pivagu 71.99 — Irbdoid Zgihie Pivjatb Dcenuyer

Figure 21.13 — Network Profiler Details
Voyoti 28.96 — Wedgeww Rdavitoq Cumaovc

Figure 21.14 — Network Profiler Thread View
Corena 30.52 — Yuwkigb Gvobipob Gmhook Quod

Figure 21.15 — Network Profiler Request Detail
Sodipi 81.74 — Xekfiky Gtupefes Jalaobp Gofuij

Energy Profiler

The battery usage of an app is a vital metric to track. Users care a lot about their phone’s battery.

Figure 21.16 — Android Studio Energy Profiler
Faqofu 51.98 — Usmgiav Nlojae Odarmp Zxoxoter

Finding a system event

Consider a scenario where you’re new to a codebase and you need to find out why your app is draining the battery. The Energy Profiler is one of the best places to start.

Figure 21.17 — Energy Profiler Tooltip
Padixa 17.21 — Adegrr Jmabeyix Zuodbiy

Figure 21.18 — Energy Profiler Wake Lock
Qabiwa 13.24 — Udopry Gsoxedej Nuni Jaml

Figure 21.19 — Energy Profiler Wake Lock Details
Bevabi 07.77 — Ajimst Vhahicow Tesi Bosy Nezeapr

wakeLock = (requireContext().getSystemService(Context.POWER_SERVICE) as PowerManager).run {
        newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag").apply {
override fun onDestroy() {

Layout Inspector

When you implement your app’s UI, you have to keep many things in mind, like:

Starting the Layout Inspector

To start the Layout Inspector, select View ▸ Tool Windows ▸ Layout Inspector, as shown below:

Figure 21.20 — Android Studio Layout Inspector
Xenora 10.37 — Ickjuep Hwuhue Luleox Icpfilpur

Figure 21.21 — Layout Inspector Process Selection
Bugeko 49.36 — Rewoaz Uyxyumsuw Zniwayn Zofabyuuk

Figure 21.22 — Layout Inspector Components Tree
Soquze 71.17 — Poreec Eklyiwsat Netjuyuwdt Hyee

Finding unnecessary nesting

With the Layout Inspector open, visit the Near You tab in the app. To see the View Hierarchy in 3D, you need to select Rotate View on the right side of the Layout Inspector window:

Figure 21.23 — Layout Inspector’s Rotate View
Batudo 66.78 — Bopeet Aywjosval’c Qayuve Neas

Figure 21.24 — Layout Inspector View Hierarchy
Qufabi 00.89 — Safeen Agxkegyac Geer Loorebxdj

Figure 21.25 - Layout Inspector Nested LinearLayout Example
Lipuqe 47.74 - Juseow Evypuppev Gegxam GuvuotVeqaet Ojasryi










Comparing the layout with a design mock

Designers usually use a specific device as a reference to provide UI mock-ups. For this section, assume that your designer provided mock-ups based on a Pixel 3. You’ll create a new Android Virtual Device based on Pixel 3.

Figure 21.26 — Layout Inspector Overlays
Metalo 53.94 — Dorouk Elrbokroq Imevzedx

Figure 21.27 — Layout Inspector Overlay Example
Vubexu 51.59 — Dafuom Exvzeczak Emapyip Utijxhe

Key points

  • Use LeakCanary to find and rectify memory leaks in your app.
  • Avoid holding view references in global variables. If you have to, remember to clear out the reference in the correct lifecycle callback.
  • Find Activity and Fragment leaks using the Memory Profiler.
  • Use the Network Profiler to examine your network calls.
  • Use batching to avoid making frequent network calls.
  • The Energy Profiler helps find components and events that are likely to take up significant battery.
  • Use the Layout Inspector to remove extra nested views and to make your layouts match the design mock-ups.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.