Saturday, March 31, 2018

How to Debug A Pre-built APK

Android Studio 3.0 added a nifty little feature -- The ability to debug and profile pre-built APK's. For developers working with a mix of Native (C/C++) and Java code for their applications, this is an extremely valuable feature.

I stumbled upon it, while I was looking for something else. Wrote this post with the intent that more people will be able to find this feature and make good use of it!

Here are the steps needed to debug a pre-built apk:
  • On the launch screen of Android Studio 3.0+, select the option "Profile or debug APK"
 

  • It will open up a dialog which will let you choose the APK you want to debug.
  • Ensure that the APK is build with debugging enabled
  • Next, Android Studio will try and create a new project in this folder ~/ApkProjects
  • Once it finishes loading the APK it will open up a screen that looks like this
  • As you can see it has unpacked the APK. It shows various part of the APK along with their sizes.
  • It has not fully decompiled *.dex files into *.java files. It show them as *.smali files. 
  • When you open the *.smali file, it will give you an opportunity to Attack Java Sources
 
  • Clicking the link Attach Java Sources will open up a dialog which will let you select the folder where Java sources are located.
  • Once you do this, you should see the Java classes in their full glory. You can now attach breakpoints and debug through the APK as if it was real source code.
  • If your project contains native code, it will let you attach a library containing debug symbols for that too.
  • Hitting the Debug or Run icons on the IDE will popup a dialog which lets you select the Device on which you want to install the APK and start debugging.

  • On selecting the device, IDE will install APK on the device and attach the debugger.
  • You should see a screen like this on the device

  • In a second or so, you should see your app's first screen loaded and ready to be debugged!
  • That's about all that is needed, you can debug, step through the code, evaluate variables and what not!
As you can see its a valuable little feature which can help in locating the bug in tricky situations!

2 comments:

  1. Hi, for me there is no "Attach Java Sources" link. Is there a way to attach java via options ?
    Thank you!

    ReplyDelete
    Replies
    1. Problem fixed. I had to disable the smalidea plugin.

      Delete

Have some Fun!