Android app debugging tools

Debugging

In this document

The Android SDK provides most of the tools that you need to debug your applications. You need a JDWP-compliant debugger if you want to be able to do things such as step through code, view variable values, and pause execution of an application. If you are using Android Studio, a JDWP-compliant debugger is already included and there is no setup required. If you are using another IDE, you can use the debugger that comes with it and attach the debugger to a special port so it can communicate with the application VMs on your devices. The main components that comprise a typical Android debugging environment are:

adb adb acts as a middleman between a device and your development system. It provides various device management capabilities, including moving and syncing files to the emulator, running a UNIX shell on the device or emulator, and providing a general means to communicate with connected emulators and devices. Dalvik Debug Monitor Server DDMS is a graphical program that communicates with your devices through adb . DDMS can capture screenshots, gather thread and stack information, spoof incoming calls and SMS messages, and has many other features. Device or Android Virtual Device Your application must run in a device or in an AVD so that it can be debugged. An adb device daemon runs on the device or emulator and provides a means for the adb host daemon to communicate with the device or emulator. JDWP debugger The Dalvik VM (Virtual Machine) supports the JDWP protocol to allow debuggers to attach to a VM. Each application runs in a VM and exposes a unique port that you can attach a debugger to via DDMS. If you want to debug multiple applications, attaching to each port might become tedious, so DDMS provides a port forwarding feature that can forward a specific VM’s debugging port to port 8700. You can switch freely from application to application by highlighting it in the Devices tab of DDMS. DDMS forwards the appropriate port to port 8700. Most modern Java IDEs include a JDWP debugger, or you can use a command line debugger such as jdb .

Debugging Environment

Figure 1 shows how the various debugging tools work together in a typical debugging environment.

Figure 1. Debugging Workflow

On your emulator or device, each application runs in its own instance of a Dalvik VM. The adb device daemon allows communication with the VMs from an outside party.

On your development machine, the adb host daemon communicates with the adb device daemon and allows tools such as DDMS to communicate with the device or emulator. The adb host daemon also allows you to access shell commands on the device as well as providing capabilities such as application installation and file transferring.

Each application VM on the device or emulator exposes a debugging port that you can attach to via DDMS. DDMS can forward any of these ports to a static debugging port (typically port 8700) by selecting the application that you want to debug in the DDMS user interface. A JDWP debugger can attach to this static debugging port and debug all the applications that are running on the device or emulator without having to attach to multiple ports.

If you are using Android Studio, much of these interconnections are hidden from you. DDMS, adb , and a JDWP debugger are all setup for you and you can access them through the Debug and DDMS view. If you are developing with another IDE environment, you may have to invoke these tools manually.

Additional Debugging Tools

In addition to the main debugging tools, the Android SDK provides additional tools to help you debug and profile your applications:

Heirarchy Viewer and layoutopt Graphical programs that let you debug and profile user interfaces. Traceview A graphical viewer that displays trace file data for method calls and times saved by your application, which can help you profile the performance of your application. Dev Tools Android application The Dev Tools application included in the emulator system image exposes several settings that provide useful information such as CPU usage and frame rate. You can also transfer the application to a hardware device.

Debugging Tips

While debugging, keep these helpful tips in mind to help you figure out common problems with your applications:

Источник

Отладка приложений для Android без исходного кода на Java

О чем статья

В этой статье я сжато, без «воды», расскажу как отлаживать приложения для Android не имея их исходного кода на Java. Статья не совсем для новичков. Она пригодиться прежде всего тем кто более или менее понимает синтаксис Smali и имеет некоторый опыт в reversing engineering приложений для Android.

Читайте также:  Android ice cream sandwich что это такое

Инструменты

Нам понадобится Apk-tool 1.4.1 и NetBeans 6.8. Да-да, именно эти древние версии! С более новыми версиями отладка к сожалению «не заводится», о чем уже неоднократно упоминалось в различных обсуждениях (см. например тут и тут).

На установке подробно не останавливаюсь. NetBeans устанавливается по умолчанию, просто запускам инсталляцию и кликаем Next-Next-Next. Установка Apk-tools заключается в обычной распаковке файла apktool.jar в любую папку.

Также по ходу дела нам понадобится DDMS — он есть в Android SDK.

Отладка

В этом разделе дана пошаговая инструкция. Она писалась для Windows, но вероятно сработает и на Linux и Mac OS. Черновик этой инструкции на английском также есть у меня в блоге, но ссылку не дам, ибо правила. Эта инструкция более или менее повторяет оригинальную инструкцию с Apk-tool wiki, однако содержит некоторые дополнительные пункты, без которых отладка может «не завестись». В своё время у меня не заводилась, и я нашел эти дополнительные пункты методом усиленного гугления и «научного тыка». Надеюсь, теперь мой опыт кому-то сэкономит время.

Пожалуйста, следуйте инструкции в точности – это важно!

    Декодируйте свой .apk файл в директорию out с помощью Apk-tool. Для этого используйте опцию -d :

В результате в директории out/smali у вас будет куча .java файлов с закомментированным Smali кодом внутри. Это нормально, так и должно быть.

  • Добавьте атрибут android:debuggable=»true» в секцию файла out/AndroidManifest.xml
  • Соберите директорию out обратно в .apk файл:

  • Подпишите файл my.app.to.debug.apk и установите его на реальное устройство или эмулятор, на котором вы собираетесь его отлаживать.
  • Удалите директорию out/build (она может помешать создать проект на шаге 6 и 7).
  • Запустите NetBeans, кликните «File» -> «New Project». Выберите «Java» -> «Java Project with Existing Sources». Кликните «Next».
  • Укажите out в качестве «Project Folder». Кликните «Next».
  • Добавьте директорию out/smali в список «Source Package Folder». Кликните «Next», а затем «Finish». В результате в проект будут добавлены те самые .java файлы с закомментированным Smali кодом внутри.
  • Запустите my.app.to.debug.apk на реальном устройстве или эмуляторе (если вы используете реальное устройство, то убедитесь что оно подключено к вашему компьютеры с помощью USB кабеля и ваша система его «видит»).
  • Запустите DDMS, найдите своё приложение в списке и кликните на него. Запомните информацию в последней колонке, это номер порта, обычно что-то вроде 86xx/8700 .
  • В Netbeans кликните «Debug» -> «Attach Debugger» -> выберите «JPDA» и введите в поле «Port» 8700 (или какой там номер порта у вас был на предыдущем шаге). Остальные поля оставте без изменений. Кликните «OK».
  • Теперь вы можете отлаживать приложение: на панели Netbeans станет можно кликать на соответствующие кнопки
  • Установите breakpoint на интересующую вас инструкцию (да-да, на одну из тех инструкция из закомментированного Smali кода внутри тех самых .java файлов о которых я уже дважды до этого упоминал). Помните, что вы не можете устанавливать breakpoints на строчки начинающиеся с «.», «:» или «#». Только на инструкции Smali кода!
  • Сделайте что-нибудь в приложении, что бы ваша breakpoint сработала. После этого вы сможете делать пошаговую отладку, просматривать значения полей и переменных и т.д.
  • Вот и всё, если вкратце.

    Подводные камни

    Без подвоха тут конечно никак. Обычно всё идёт хорошо, строго по инструкции, аж до шага 13. А вот на шаге 13 люди часто ставят breakpoint в самом начале кода приложения: например в методе onCreate(. ) в activity с которой начинается выполнение приложения. Оно вроде бы и логично – если не совсем понятно откуда начинать отлаживать приложение, лучше начинать с самого начала. Однако в большинстве случаев дело не идёт. Отлаживаемое приложение работает себе как ни в чем не бывало, а подлый breakpoint в onCreate(. ) ни в какую не желает срабатывать.

    Это происходит из-за того что мы подсоединяем отладчик к уже работающему приложению. Это значит код в начале приложения (например в том же методе onCreate в activity с которой начинается выполнение приложения) уже выполнился, и ставить на него breakpoint’ы как правило (хотя не всегда конечно) бесполезно. Более того, когда мы присоединяем отладчик к работающему приложению, оно не останавливается пока не сработает наш breakpoint или пока мы его сами не остановим – об этом моменте также стоит помнить.

    В своей следующей статье я показываю трюк, который позволяет отлаживать Java приложения для Android без исходного кода с самого начала, т.е. именно с того самого первого метода onCreate(. ) (или даже конструктора) в activity с которой начинается выполнение приложения.

    Если есть вопросы – пожалуйста задавайте их в комментариях или в личных сообщениях. Постараюсь ответить по-возможности оперативно, но если буду тупить – пожалуйста наберитесь терпения. Постараюсь ответить всем.

    Источник

    Debugging with Android Studio

    In this document

    See also

    Android Studio enables you to debug apps running on the emulator or on an Android device. With Android Studio, you can:

    • Select a device to debug your app on.
    • View the system log.
    • Set breakpoints in your code.
    • Examine variables and evaluate expressions at run time.
    • Run the debugging tools from the Android SDK.
    • Capture screenshots and videos of your app.

    To debug your app, Android Studio builds a debuggable version of your app, connects to a device or to the emulator, installs the app and runs it. The IDE shows the system log while your app is running and provides debugging tools to filter log messages, work with breakpoints, and control the execution flow.

    Читайте также:  Модуль для зарядки андроид

    Run your App in Debug Mode

    Figure 1. The Choose Device window enables you to select a physical Android device or a virtual device to debug your app.

    To run your app in debug mode, you build an APK signed with a debug key and install it on a physical Android device or on the Android emulator. To set up an Android device for development, see Using Hardware Devices. For more information about the emulator provided by the Android SDK, see Using the Emulator.

    To debug your app in Android Studio:

    1. Open your project in Android Studio.
    2. Click Debug in the toolbar.
    3. On the Choose Device window, select a hardware device from the list or choose a virtual device.
    4. Click OK. Your app starts on the selected device.

    Figure 1 shows the Choose Device window. The list shows all the Android devices connected to your computer. Select Launch Emulator to use an Android virtual device instead. Click the ellipsis to open the Android Virtual Device Manager.

    Android Studio opens the Debug tool window when you debug your app. To open the Debug window manually, click Debug . This window shows threads and variables in the Debugger tab, the device status in the Console tab, and the system log in the Logcat tab. The Debug tool window also provides other debugging tools covered in the following sections.

    Figure 2. The Debug tool window in Android Studio showing the current thread and the object tree for a variable.

    Attach the debugger to a running process

    You don’t always have to restart your app to debug it. To debug an app that you’re already running:

    1. Click Attach debugger to Android proccess.
    2. In the Choose Process window, select the device and app you want to attach the debugger to.
    3. To open the Debug tool window, click Debug .

    Use the System Log

    The system log shows system messages while you debug your app. These messages include information from apps running on the device. If you want to use the system log to debug your app, make sure your code writes log messages and prints the stack trace for exceptions while your app is in the development phase.

    Write log messages in your code

    To write log messages in your code, use the Log class. Log messages help you understand the execution flow by collecting the system debug output while you interact with your app. Log messages can tell you what part of your application failed. For more information about logging, see Reading and Writing Logs.

    The following example shows how you might add log messages to determine if previous state information is available when your activity starts:

    During development, your code can also catch exceptions and write the stack trace to the system log:

    Note: Remove debug log messages and stack trace print calls from your code when you are ready to publish your app. You could do this by setting a DEBUG flag and placing debug log messages inside conditional statements.

    View the system log

    Both the Android DDMS (Dalvik Debug Monitor Server) and the Debug tool windows show the system log; however, the Android DDMS tool window lets you view only log messages for a particular process. To view the system log on the Android DDMS tool window:

    1. Start your app as described in Run your App in Debug Mode.
    2. Click Androidto open the Android DDMS tool window.
    3. If the system log is empty in the Logcat view, click Restart.

    Figure 4. The system log in the Android DDMS tool window.

    The Android DDMS tool window gives you access to some DDMS features from Android Studio. For more information about DDMS, see Using DDMS.

    The system log shows messages from Android services and other Android apps. To filter the log messages to view only the ones you are interested in, use the tools in the Android DDMS window:

    • To show only log messages for a particular process, select the process in the Devices view and then click Only Show Logcat from Selected Process. If the Devices view is not available, click Restore Devices Viewon the right of the Android DDMS tool window. This button is only visible when you hide the Devices window.
    • To filter log messages by log level, select a level under Log Level on the top of the Android DDMS window.
    • To show only log messages that contain a particular string, enter the string in the search box and press Enter.

    Work with Breakpoints

    Breakpoints enable you to pause the execution of your app at a particular line of code, examine variables, evaluate expressions, and continue the execution line by line. Use breakpoints to determine the causes of run-time errors that you can’t fix by looking at your code only. To debug your app using breakpoints:

    1. Open the source file in which you want to set a breakpoint.
    2. Locate the line where you want to set a breakpoint and click on it.
    3. Click on the yellow portion of the side bar to the left of this line, as shown in figure 5.
    4. Start your app as described in Run your App in Debug Mode.
    Читайте также:  Кто создал android компания

    Android Studio pauses the execution of your app when it reaches the breakpoint. You can then use the tools in the Debug tool window to identify the cause of the error.

    Figure 5. A red dot appears next to the line when you set a breakpoint.

    View and configure breakpoints

    To view all the breakpoints and configure breakpoint settings, click View Breakpoints on the left side of the Debug tool window. The Breakpoints window appears, as shown in figure 6.

    Figure 6. The Breakpoints window lists all the current breakpoints and includes behavior settings for each.

    The Breakpoints window lets you enable or disable each breakpoint from the list on the left. If a breakpoint is disabled, Android Studio does not pause your app when it hits that breakpoint. Select a breakpoint from the list to configure its settings. You can configure a breakpoint to be disabled at first and have the system enable it after a different breakpoint is hit. You can also configure whether a breakpoint should be disabled after it is hit. To set a breakpoint for any exception, select Exception Breakpoints in the list of breakpoints.

    Debug your app with breakpoints

    After you set breakpoints in your code, click Rerun to start the app again. When a breakpoint is hit, Android Studio pauses the app and highlights the breakpoint in the source code. The Debug tool window lets you examine variables and control the execution step by step:

    To examine the object tree for a variable, expand it in the Variables view. If the Variables view is not visible, click Restore Variables View .

    To evaluate an expression at the current execution point, click Evaluate Expression .

    To advance to the next line in the code (without entering a method), click Step Over .

    To advance to the first line inside a method call, click Step Into .

    To advance to the next line outside the current method, click Step Out .

    To continue running the app normally, click Resume Program .

    Figure 7. The Variables view in the Debug tool window.

    Track Object Allocation

    Android Studio lets you track objects that are being allocated on the Java heap and see which classes and threads are allocating these objects. This allows you to see the list of objects allocated during a period of interest. This information is valuable for assessing memory usage that can affect application performance.

    To track memory allocation of objects:

    1. Start your app as described in Run Your App in Debug Mode.
    2. Click Androidto open the Android DDMS tool window.
    3. On the Android DDMS tool window, select the Devices | logcat tab.
    4. Select your device from the dropdown list.
    5. Select your app by its package name from the list of running apps.
    6. Click Start Allocation Tracking
    7. Interact with your app on the device.
    8. Click Stop Allocation Tracking

    Android Studio shows the objects that the system allocated with the following information:

    • Allocation order
    • Allocated class
    • Allocation size
    • Thread ID
    • Allocation method, class, and line number
    • Stack trace at the point of allocation

    Figure 8. Object allocation tracking in Android Studio.

    Analyze Runtime Metrics to Optimize your App

    Even if your application does not generate runtime errors, this does not mean it is free of problems. You should also consider the following issues:

    • Does your app use memory efficiently?
    • Does your app generate unnecessary network traffic?
    • What methods should you focus your attention on to improve the performance of your app?
    • Does your app behave properly when the user receives a phone call or a message?

    The Android Device Monitor is a stand-alone tool with a graphical user interface for serveral Android application debugging and analysis tools, including the Dalvik Debug Monitor Server (DDMS). You can use the Android Device Monitor to analyze memory usage, profile methods, monitor network traffic and simulate incoming calls and messages.

    To open the Android Device Monitor from Android Studio, click Monitor on the toolbar. The Android Device Monitor opens in a new window.

    For more information about the Android Device Monitor and DDMS, see Device Monitor and Using DDMS.

    Capture Screenshots and Videos

    Android Studio enables you to capture a screenshot or a short video of the device screen while your app is running. Screenshots and videos are useful as promotional materials for your app, and you can also attach them to bug reports that you send to your development team.

    To take a screenshot of your app:

    1. Start your app as described in Run your App in Debug Mode.
    2. Click Androidto open the Android DDMS tool window.
    3. Click Screen Captureon the left side of the Android DDMS tool window.
    4. Optional: To add a device frame around your screenshot, enable the Frame screenshot option.
    5. Click Save.

    To take a video recording of your app:

    1. Start your app as described in Run your App in Debug Mode.
    2. Click Androidto open the Android DDMS tool window.
    3. Click Screen Recordon the left side of the Android DDMS tool window.
    4. Click Start Recording.
    5. Interact with your app.
    6. Click Stop Recording.
    7. Enter a file name for the recording and click OK.

    Источник

    Оцените статью