In this document
- Use the System Log
- Work with Breakpoints
Android ships with a debugging tool called the Dalvik Debug Monitor Service (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. DDMS DDMS stands for Dalvik debug monitor server, that provide many services on the device. The service could include message formation, call spoofing, capturing screenshot, exploring internal threads and file systems e.t.c Running DDMS From Andro.
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, connectsto a device or to the emulator, installs the app and runs it. The IDE shows the system logwhile your app is running and provides debugging tools to filter log messages, work withbreakpoints, 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 aphysical Android device or on the Android emulator.To set up an Android device for development, see UsingHardware Devices. For more information about the emulator provided by the Android SDK, seeUsing the Emulator.
To debug your app in Android Studio:
- Open your project in Android Studio.
- Click Debug in the toolbar.
- On the Choose Device window, select a hardware device from the list or choose a virtual device.
- Click OK. Your app starts on the selected device.
Figure 1 shows the Choose Device window. The list shows all the Android devicesconnected to your computer. Select Launch Emulator to use an Android virtual deviceinstead. Click the ellipsis to open theAndroid Virtual Device Manager.
Android Studio opens the Debug tool window when you debug your app. To open theDebug window manually, click Debug.This window shows threads and variables in the Debugger tab, the device status in theConsole tab, and the system log in the Logcat tab. The Debug toolwindow also provides other debugging tools covered in the following sections.
Figure 2. The Debug tool window in Android Studio showingthe current thread and the object tree for a variable.
Use the System Log
The system log shows system messages while you debug your app. These messages includeinformation from apps running on the device. If you want to use thesystem log to debug your app, make sure your code writes log messages and prints the stacktrace 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 messageshelp you understand the execution flow by collecting the system debug output while you interactwith your app. Log messages can tell you what part of your application failed. For moreinformation about logging, see Reading and Writing Logs.
The following example shows how you might add log messages to determine if previous stateinformation is available when your activity starts:
During development, your code can also catch exceptions and write the stack trace to the systemlog:
Note: Remove debug log messages and stack trace print calls fromyour 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 windowsshow the system log; however, the Android DDMS tool window lets you view only log messagesfor a particular process. To view the system log on the Android DDMS tool window:
- Start your app as described in Run your App in Debug Mode.
- Click Android to open the Android DDMS tool window.
- If the system log is empty in the Logcat view, click Restart .
Figure 4. The system log in the Android DDMS toolwindow.
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 logmessages to view only the ones you are interested in, use the tools in the Android DDMSwindow:
- 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 View on 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, examinevariables, evaluate expressions, and continue the execution line by line. Use breakpoints todetermine the causes of run-time errors that you can't fix by looking at your code only. To debugyour app using breakpoints:
- Open the source file in which you want to set a breakpoint.
- Locate the line where you want to set a breakpoint and click on it.
- Click on the yellow portion of the side bar to the left of this line, as shown in figure 5.
- Start your app as described in Run your App in Debug Mode.
Android Studio pauses the execution of your app when it reaches the breakpoint. You can thenuse 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 seta breakpoint.
View and configure breakpoints
To view all the breakpoints and configure breakpoint settings, click ViewBreakpoints on the left side of the Debug toolwindow. The Breakpoints window appears, as shown in figure 6.
Figure 6. The Breakpoints window lists all the currentbreakpoints and includes behavior settings for each.
The Breakpoints window lets you enable or disable each breakpoint from thelist on the left. If a breakpoint is disabled, Android Studio does not pause your app whenit 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 adifferent breakpoint is hit. You can also configure whether a breakpoint should be disabled afterit is hit. To set a breakpoint for any exception, select Exception Breakpointsin 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 ishit, Android Studio pauses the app and highlights the breakpoint in the source code. TheDebug tool window lets you examine variables and control the execution step bystep:
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 whichclasses and threads are allocating these objects. This allows you to see the list of objectsallocated during a period of interest. This information is valuable for assessing memory usagethat can affect application performance.
To track memory allocation of objects:
- Start your app as described in Run Your App in Debug Mode.
- Click Android to open the Android DDMStool window.
- On the Android DDMS tool window, select the Devices | logcat tab.
- Select your device from the dropdown list.
- Select your app by its package name from the list of running apps.
- Click Start Allocation Tracking
- Interact with your app on the device.
- 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 ofproblems. 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 serveralAndroid 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, clickMonitor on the toolbar. The Android Device Monitoropens in a new window.
For more information about the Android Device Monitor and DDMS, seeDevice Monitor andUsing DDMS.
Capture Screenshots and Videos
Android Studio enables you to capture a screenshot or a short video of the device screenwhile your app is running. Screenshots and videos are useful as promotional materials for yourapp, and you can also attach them to bug reports that you send to your development team.
To take a screenshot of your app:
- Start your app as described in Run your App in Debug Mode.
- Click Android to open the Android DDMS tool window.
- Click Screen Capture on the left side of the Android DDMS tool window.
- Optional: To add a device frame around your screenshot, enable the Frame screenshot option.
- Click Save.
To take a video recording of your app:
- Start your app as described in Run your App in Debug Mode.
- Click Android to open the Android DDMS tool window.
- Click Screen Record on the left side of the Android DDMS tool window.
- Click Start Recording.
- Interact with your app.
- Click Stop Recording.
- Enter a file name for the recording and click OK.
In this document
- Using DDMS
Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. This page provides a modest discussion of DDMS features; it is not an exhaustive exploration of all the features and capabilities.
Running DDMS
DDMS is integrated into Eclipse and is also shipped in the tools/
directory of the SDK. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, DDMS defaults to the emulator.
- From Eclipse: Click Window > Open Perspective > Other... > DDMS.
- From the command line: Type
ddms
(or./ddms
on Mac/Linux) from thetools/
directory.
How DDMS Interacts with a Debugger
On Android, every application runs in its own process, each of which runs in its own virtual machine (VM). Each VM exposes a unique port that a debugger can attach to.
When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb
and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb
, and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a custom wire protocol.
DDMS assigns a debugging port to each VM on the device. Typically, DDMS assigns port 8600 for the first debuggable VM, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded to the debugger from the associated VM. You can only attach a single debugger to a single port, but DDMS can handle multiple, attached debuggers.
By default, DDMS also listens on another debugging port, the DDMS 'base port' (8700, by default). The base port is a port forwarder, which can accept VM traffic from any debugging port and forward it to the debugger on port 8700. This allows you to attach one debugger to port 8700, and debug all the VMs on a device. The traffic that is forwarded is determined by the currently selected process in the DDMS Devices view.
The following screenshot shows a typical DDMS screen in Eclipse. If you are starting DDMS from the command line, the screen is slightly different, but much of the functionality is identical. Notice that the highlighted process, com.android.email
, that is running in the emulator has the debugging port 8700 assigned to it as well as 8606. This signifies that DDMS is currently forwarding port 8606 to the static debugging port of 8700.
Figure 1. Screenshot of DDMS
If you are not using Eclipse and ADT, read Configuring your IDE to attach to the debugging port, for more information on attaching your debugger.
Tip: You can set a number of DDMS preferences in File > Preferences. Preferences are saved to $HOME/.android/ddms.cfg
.
Known debugging issues with Dalvik
Debugging an application in the Dalvik VM should work the same as it does in other VMs. However, when single-stepping out of synchronized code, the 'current line' cursor may jump to the last line in the method for one step.
Using DDMS
The following sections describe how to use DDMS and the various tabs and panes that are part of the DDMS GUI. The Eclipse version and the command line version have minor UI differences, but the same functionality. For information on running DDMS, see the previous section in this document, Running DDMS.Viewing heap usage for a process
DDMS allows you to view how much heap memory a process is using. This information is useful in tracking heap usage at a certain point of time during the execution of your application.
Dalvik Debug Monitor Services
To view heap usage for a process:
- In the Devices tab, select the process that you want to see the heap information for.
- Click the Update Heap button to enable heap information for the process.
- In the Heap tab, click Cause GC to invoke garbage collection, which enables the collection of heap data. When the operation completes, you will see a group of object types and the memory that has been allocated for each type. You can click Cause GC again to refresh the data.
- Click on an object type in the list to see a bar graph that shows the number of objects allocated for a particular memory size in bytes.
Tracking memory allocation of objects
DDMS provides a feature to track objects that are being allocated to memory and to see which classes and threads are allocating the objects. This allows you to track, in real time, where objects are being allocated when you perform certain actions in your application. This information is valuable for assessing memory usage that can affect application performance.
To track memory allocation of objects:
- In the Devices tab, select the process that you want to enable allocation tracking for.
- In the Allocation Tracker tab, click the Start Tracking button to begin allocation tracking. At this point, anything you do in your application will be tracked.
- Click Get Allocations to see a list of objects that have been allocated since you clicked on the Start Tracking button. You can click on Get Allocations again to append to the list new objects that that have been allocated.
- To stop tracking or to clear the data and start over, click the Stop Tracking button.
- Click on a specific row in the list to see more detailed information such as the method and line number of the code that allocated the object.
Working with an emulator or device's file system
DDMS provides a File Explorer tab that allows you to view, copy, and delete files on the device. This feature is useful in examining files that are created by your application or if you want to transfer files to and from the device.
To work with an emulator or device's file system:
- In the Devices tab, select the emulator that you want to view the file system for.
- To copy a file from the device, locate the file in the File Explorer and click the Pull file button.
- To copy a file to the device, click the Push file button on the File Explorer tab.
Examining thread information
The Threads tab in DDMS shows you the currently running threads for a selected process.
- In the Devices tab, select the process that you want to examine the threads for.
- Click the Update Threads button.
- In the Threads tab, you can view the thread information for the selected process.
Starting method profiling
Method profiling is a means to track certain metrics about a method, such as number of calls, execution time, and time spent executing the method. If you want more granular control over where profiling data is collected, use the startMethodTracing()
and stopMethodTracing()
methods. For more information about generating trace logs, see Profiling and Debugging UIs.
Before you start method profiling in DDMS, be aware of the following restrictions:
- Android 1.5 devices are not supported.
- Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card.
- Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.
To start method profiling:
- On the Devices tab, select the process that you want to enable method profiling for.
- Click the Start Method Profiling button.
- Interact with your application to start the methods that you want to profile.
- Click the Stop Method Profiling button. DDMS stops profiling your application and opens Traceview with the method profiling information that was collected between the time you clicked on Start Method Profiling and Stop Method Profiling.
Using the Network Traffic tool
In Android 4.0, the DDMS (Dalvik Debug Monitor Server) includes a DetailedNetwork Usage tab that makes it possible to track when your application ismaking network requests. Using this tool, you can monitor how and when your apptransfers data and optimize the underlying code appropriately. You can alsodistinguish between different traffic types by applying a “tag” to networksockets before use.
These tags are shown in a stack area chart in DDMS, as shown in figure 2:
Figure 2. Network Usage tab.
By monitoring the frequency of your data transfers, and the amount of datatransferred during each connection, you can identify areas of your applicationthat can be made more battery-efficient. Generally, you should look forshort spikes that can be delayed, or that should cause a later transfer to bepre-empted.
To better identify the cause of transfer spikes, theTrafficStats
API allows youto tag the data transfers occurring within a thread using setThreadStatsTag()
, followedby manually tagging (and untagging) individual sockets using tagSocket()
and untagSocket()
. For example:
Alternatively, the Apache HttpClient
and URLConnection
APIs included in the platformautomatically tag sockets internally based on the active tag (as identified by getThreadStatsTag()
).These APIs correctly tag/untag sockets when recycled throughkeep-alive pools. In the following example, setThreadStatsTag()
sets the active tag to be 0xF00D
. There can only be one active tag per thread. That is the value that will be returned by getThreadStatsTag()
and thus used by HttpClient
to tag sockets. The finally
statement invokes clearThreadStatsTag()
to clear the tag.
Socket tagging is supported in Android 4.0, but real-time stats will only bedisplayed on devices running Android 4.0.3 or higher.
Using LogCat
LogCat is integrated into DDMS, and outputs the messages that you print out using the Log
class along with other system messages such as stack traces when exceptions are thrown. View the Reading and Writing Log Messages. topic for more information on how to log messages to the LogCat.
When you have set up your logging, you can use the LogCat feature of DDMS to filter certain messages with the following buttons:
- Verbose
- Debug
- Info
- Warn
- Error
You can also setup your own custom filter to specify more details such as filtering messages with the log tags or with the process id that generated the log message. The add filter, edit filter, and delete filter buttons let you manage your custom filters.
Emulating phone operations and location
The Emulator control tab lets you simulate a phone's voice and data network status. This is useful when you want to test your application's robustness in differing network environments.
Changing network state, speed, and latency
Dalvik Debug Monitor Server
The Telephony Status section of the Emulator controls tab lets you change different aspects of the phone's networks status, speed and latency. The following options are available to you and are effective immediately after you set them:
- Voice - unregistered, home, roaming, searching, denied
- Data - unregistered, home, roaming, searching, denied
- Speed - Full, GSM, HSCSD, GPRS, EDGE, UMTS, HSDPA
- Latency - GPRS, EDGE, UMTS
Spoofing calls or SMS text messages
The Telephony Actions section of the Emulator controls tab lets you spoof calls and messages. This is useful when you want to to test your application's robustness in responding to incoming calls and messages that are sent to the phone. The following actions are available to you:
- Voice - Enter a number in the Incoming number field and click Call to send a simulated call to the emulator or phone. Click the Hang up button to terminate the call.
- SMS - Enter a number in the Incoming number field and a message in the Message: field and click the Send button to send the message.
Setting the location of the phone
If your application depends on the location of the phone, you can have DDMS send your device or AVD a mock location. This is useful if you want to test different aspects of your application's location specific features without physically moving. The following geolocation data types are available to you:
- Manual - set the location by manually specifying decimal or sexagesimal longitude and latitude values.
- GPX - GPS eXchange file
- KML - Keyhole Markup Language file