SlideShare a Scribd company logo
1
ANDROID NÂNG CAOANDROID NÂNG CAO
Bài 9:
Debugging inDebugging in
Android Application DevelopmentAndroid Application Development
Debug Environment
Dev Tools Android application
Hierarchy Viewer & layoutopt
Traceview & Method profiling
ANR & StrictMode
Agenda
jhat & Heap Profiling
Debug Environment
Android Debug Bridge
Model:
 Client
 Server
Components
A client
A server
A daemon
Important commands:
-d/-e/-s
devices.
install/uninstall.
pull/push
forward
shell
logcat
kill-server
Client
1
Client
2
Server
Daemon
1
Daemon
2
Daemon
31
5037
5037
5555/5554
5585/5584
5557/5556
UI/Application Exercise Monkey
The Monkey: generates pseudo-random streams of user events
Application: stress-test applications
Detect application crashes or receives any sort of unhandled
exception.
ANR error.
Basic usage:
$ adb shell monkey [options] <event-count>
 Sample:
$ adb shell monkey -p your.package.name -v 500
 Reference:
http://developer.android.com/guide/developing/tools/monkey.html
Dalvik Debug Monitor Server
 2 ways to start DDMS:
 Command line.
 Show DDMS perspective in Eclipse.
 Using:
 Monitoring:
 Viewing heap usage for a process.
 Tracking memory allocation of objects.
 Examining thread information.
 Starting method profiling.
 Using LogCat.
 File operation
 Work with emulator or device’s file system.
 Emulating phone operations and location
 Changing network state, speed, latency.
 Spoofing calls or SMS text messages.
 Setting the location of phone.
 Process Management
 Execute garbage collection
 Interrupt process
 Reference:
http://developer.android.com/guide/developing/debugging/ddms.html
adb logcat command
Use to view & follow the content of system log’s buffer.
Filter log output:
Using filter expression: tag:priority … tag:priority
Controll log output format:
Using –v switch: brief, process, tag, thread, raw, time, long.
Viewing Alternative Log Buffers :
Using –b switch: radio, event, main.
Viewing stdout and stderr:
setprop log.redirect-stdio true or edit /data/local.prop
Reference:
http://developer.android.com/guide/developing/tools/adb.html
Device
DDMS & Debuggers
DDMS adb
Connect
VM monitoring service
VM
JDWP
Debugger
(jdb)
VM start/stop
adbd
VM’s PID
Monitor
8700
8600
Hierarchy Viewer & layoutopt
Purpose: Debugging & profiling user interface
Tools:
Hierarchy Viewer.
layoutopt
Reference:
http://developer.android.com/guide/developing/debugging/debugging-ui.html
Hierarchy Viewer
Purpose: Debugging &optimize user interface
Running HV:
Connect your device or launch an emulator.
Install the application you want to work with.
Run the application, and ensure that its UI is visible.
Launch hierarchyviewer
The first window you see displays a list of devices and emulators.
Select the name of your Activity from the list. You can now look at
its view hierarchy using the View Hierarchy window, or look at a
magnified image of the UI using the Pixel Perfect window
Hierarchy Viewer
•TreeView:
Hierarchy Viewer
•Pixel Perfect window:
layoutopt
Purpose: analyze XML layout file to find inefficiences.
Running layoutopt: layoutopt <xmlfile>
Information display when effect is detected:
The filename
 The line number.
 The description.
TraceView & Method Profiling
 TraceView: a graphical viewer for execution logs that you create by using the Debug
class to log tracing information in your code.
 Application:
 Method profiling to find the bottle neck in your code execution.
 Usage:
 Create trace file:
 Using Debug class:
// start tracing to "/sdcard/xml.trace"
Debug.startMethodTracing(“xml");
//Call to the method you want to trace.
// stop tracing
Debug.stopMethodTracing();
 Using method profiling feature of DDMS to generate trace file.
 Copy file to host machine.
 Viewing trace file in Traceview.
 Limitation:
 Thread name is not emitted if thread exits during profiling.
 Reuses thread ID of VM.
 Reference:
http://developer.android.com/guide/developing/debugging/debugging-tracing.html
TraceView & Method Profiling
 Timeline Panel:
 Profile Panel:
dmtracedump
 Generate graphical call-stack diagram from trace log file.
Call reference number Inclusive elapsed time Exclusive elapsed time
Number of calls
dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>
jhat & Heap Profiling
 Heap Profiling helps to find the leak memory, speed up the program:
 How many instances of a class.
 How much memory usage.
 Usage:
 Set the break point:
 Exception break point.
 Conditional break point.
 Dump HPROF file from DDMS.
 Using jhat (java heap analysis tool) to parse hprof file.
 Open the favorite web browser and visit: http://localhost:7000
jhat & Heap Profiling
 Exception breakpoint:
 Run > Add Java Exception Breakpoint …
 Conditional breakpoint:
 Right click on breakpoint > Properties > Check Conditional checkbox > Enter the
condition.
Read more about MAT: http://10.1.6.46/mediawiki/index.php/Dectect_memory_leak_using_MAT
jhat & Heap Profiling
 Using DDMS dump hprof file:
 Click on “Show heap histogram”:
ANR & StrictMode
 ANR.
 Causes
 Activity
 BroadcastReceiver
 StrictMode:
public void onCreate() {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();
}
 Reference:
http://developer.android.com/guide/practices/design/responsiveness.html
Dev Tools Application
 Get it from emulator & install into real device.
 Application:
 Enable some settings in your device for testing & debugging.
 Usage:
 Launch it > Development Settings
 Debug app
 Wait for debugger
 Show screen updates
 Immediately destroy activities
 Show CPU usage
 Show background
 Reference:
http://developer.android.com/guide/developing/debugging/debugging-devtools.html
Debug Tips
 Dump the stack trace:
adb shell > ps > kill -3
 Display useful info on the emulator screen:
View Dev Tools App
 Get application and system state information from the emulator:
View dumpsys and dumpstate
 Get wireless connectivity information:
DDMS > Device menu > Dump radio state
 Log trace data:
Call startMethodTracing()
 Log radio data:
adb shell>logcat –b radio
 Capture screenshots:
DDMS> Select device >Screen Capture
 Use debugging helper classes:
Log, Debug, StrictMode
 Garbage collection:
Any object the debugger is aware of is not garbage collected until after the debugger disconnects
Nguyen Huu Phuoc, MEng.
●  Blog:http://folami.nghelong.com
●  Website http://phuocnh.nghelong.com

More Related Content

PPT
Real world cross-platform testing
PPTX
Дмитрий Демчук. Кроссплатформенный краш-репорт
PDF
안드로이드 데이터 바인딩
PPTX
Jdk(java) 7 - 6 기타기능
DOCX
Exercícios Netbeans - Vera Cymbron
PPTX
Surface flingerservice(서피스플링거서비스초기화)
PPTX
Java script for web developer
PDF
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Real world cross-platform testing
Дмитрий Демчук. Кроссплатформенный краш-репорт
안드로이드 데이터 바인딩
Jdk(java) 7 - 6 기타기능
Exercícios Netbeans - Vera Cymbron
Surface flingerservice(서피스플링거서비스초기화)
Java script for web developer
Singletons in PHP - Why they are bad and how you can eliminate them from your...

What's hot (20)

PDF
Kobold2Dで始めるゲーム開発
PPTX
Enterprise js pratices
PDF
How to make a large C++-code base manageable
PDF
Creating Alloy Widgets
PPTX
The zen of async: Best practices for best performance
PPTX
C++17 now
PDF
Symfony2 - from the trenches
PDF
Grain final border one
PDF
OSGi and Eclipse RCP
PDF
What's up with Prototype and script.aculo.us?
PDF
The Case for React.js and ClojureScript
PDF
Advanced javascript
PDF
HKG15-211: Advanced Toolchain Usage Part 4
PDF
Daggerate your code - Write your own annotation processor
PPT
ExtJs Basic Part-1
PPTX
Dynamic virtual evironments
PDF
HKG15-207: Advanced Toolchain Usage Part 3
PDF
"Node.js threads for I/O-bound tasks", Timur Shemsedinov
PDF
T-121-5300 (2008) User Interface Design 10 - UIML
Kobold2Dで始めるゲーム開発
Enterprise js pratices
How to make a large C++-code base manageable
Creating Alloy Widgets
The zen of async: Best practices for best performance
C++17 now
Symfony2 - from the trenches
Grain final border one
OSGi and Eclipse RCP
What's up with Prototype and script.aculo.us?
The Case for React.js and ClojureScript
Advanced javascript
HKG15-211: Advanced Toolchain Usage Part 4
Daggerate your code - Write your own annotation processor
ExtJs Basic Part-1
Dynamic virtual evironments
HKG15-207: Advanced Toolchain Usage Part 3
"Node.js threads for I/O-bound tasks", Timur Shemsedinov
T-121-5300 (2008) User Interface Design 10 - UIML
Ad

Viewers also liked (20)

ODP
Android Nâng cao-Bài 3: Broadcast Receiver
ODP
Android Nâng cao-Bài 4: Content Provider
ODP
Android Nâng cao-Bài 8-JSON & XML Parsing
ODP
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnit
PDF
Cách tối ưu hóa môi trường lập trình ứng dụng cho Android - Tăng tốc máy ảo A...
ODP
Android Nâng cao-Bài 5:Notification Multiresolution Multilanguage
ODP
Android location sensor programming
PDF
Android talks #08 android profiling
PPTX
Android chapter03-life-cycle
PPT
IT120-1. Giới thiệu về Android SDK
PPTX
Android ios wp7
PPTX
Google Android Security (Basic2Advanced)
PPT
Android presentation
PPT
Android chapter03-life-cycle
PPTX
Basic Sqlite in Android
PPTX
Slide hội thảo Google Android BKHN 26-10
PPTX
PPT
Lap trinh android – kiem tien ngay trong khi hoc
PPTX
Tìm hiểu về hệ điều hành android
PPT
Bài 1: Giới thiệu Android
Android Nâng cao-Bài 3: Broadcast Receiver
Android Nâng cao-Bài 4: Content Provider
Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 6-Multi theme-adb tool-jUnit
Cách tối ưu hóa môi trường lập trình ứng dụng cho Android - Tăng tốc máy ảo A...
Android Nâng cao-Bài 5:Notification Multiresolution Multilanguage
Android location sensor programming
Android talks #08 android profiling
Android chapter03-life-cycle
IT120-1. Giới thiệu về Android SDK
Android ios wp7
Google Android Security (Basic2Advanced)
Android presentation
Android chapter03-life-cycle
Basic Sqlite in Android
Slide hội thảo Google Android BKHN 26-10
Lap trinh android – kiem tien ngay trong khi hoc
Tìm hiểu về hệ điều hành android
Bài 1: Giới thiệu Android
Ad

Similar to Android Nâng cao-Bài 9-Debug in Android Application Development (20)

PPT
.NET Debugging Tips and Techniques
PPT
.Net Debugging Techniques
PPT
Jdk Tools For Performance Diagnostics
PPTX
Android tools for testers
PPT
Android developmenttools 20100424
PDF
Reversing & malware analysis training part 12 rootkit analysis
PDF
Advanced iOS Debbuging (Reloaded)
PDF
Android Logging System
PDF
Inside Android's UI at AnDevCon V
PDF
Inside Android's UI at AnDevCon VI
PPT
CHAPTER 3 BASIC DYNAMIC ANALYSIS.ppt
PPTX
Manish Chasta - Securing Android Applications
PDF
Crash dump analysis - experience sharing
PDF
PPT
Android dev
PDF
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclient
PPT
Android tools
PDF
Damage Control
PPTX
Troubleshooting real production problems
PPTX
How We Analyzed 1000 Dumps in One Day - Dina Goldshtein, Brightsource - DevOp...
.NET Debugging Tips and Techniques
.Net Debugging Techniques
Jdk Tools For Performance Diagnostics
Android tools for testers
Android developmenttools 20100424
Reversing & malware analysis training part 12 rootkit analysis
Advanced iOS Debbuging (Reloaded)
Android Logging System
Inside Android's UI at AnDevCon V
Inside Android's UI at AnDevCon VI
CHAPTER 3 BASIC DYNAMIC ANALYSIS.ppt
Manish Chasta - Securing Android Applications
Crash dump analysis - experience sharing
Android dev
Honeynet Project Workshop 2014 - Thug: a low-interaction honeyclient
Android tools
Damage Control
Troubleshooting real production problems
How We Analyzed 1000 Dumps in One Day - Dina Goldshtein, Brightsource - DevOp...

More from Phuoc Nguyen (7)

ODP
Lanh dao va TPP
PDF
Hiberbate Framework
PPTX
Introduction to Hibernate Framework
ODP
Webservice performance testing with SoapUI
ODP
Web application security test tools
ODP
A successful project sharing
ODP
Buồn vui nghề IT (Pros & cons of IT Career)
Lanh dao va TPP
Hiberbate Framework
Introduction to Hibernate Framework
Webservice performance testing with SoapUI
Web application security test tools
A successful project sharing
Buồn vui nghề IT (Pros & cons of IT Career)

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
KodekX | Application Modernization Development
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Modernizing your data center with Dell and AMD
PDF
Electronic commerce courselecture one. Pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Cloud computing and distributed systems.
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Machine learning based COVID-19 study performance prediction
20250228 LYD VKU AI Blended-Learning.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Per capita expenditure prediction using model stacking based on satellite ima...
KodekX | Application Modernization Development
Spectral efficient network and resource selection model in 5G networks
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Monthly Chronicles - July 2025
Advanced methodologies resolving dimensionality complications for autism neur...
Modernizing your data center with Dell and AMD
Electronic commerce courselecture one. Pdf
Big Data Technologies - Introduction.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Cloud computing and distributed systems.
Network Security Unit 5.pdf for BCA BBA.
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Mobile App Security Testing_ A Comprehensive Guide.pdf
cuic standard and advanced reporting.pdf
MYSQL Presentation for SQL database connectivity
Machine learning based COVID-19 study performance prediction

Android Nâng cao-Bài 9-Debug in Android Application Development

  • 1. 1 ANDROID NÂNG CAOANDROID NÂNG CAO Bài 9: Debugging inDebugging in Android Application DevelopmentAndroid Application Development
  • 2. Debug Environment Dev Tools Android application Hierarchy Viewer & layoutopt Traceview & Method profiling ANR & StrictMode Agenda jhat & Heap Profiling
  • 4. Android Debug Bridge Model:  Client  Server Components A client A server A daemon Important commands: -d/-e/-s devices. install/uninstall. pull/push forward shell logcat kill-server Client 1 Client 2 Server Daemon 1 Daemon 2 Daemon 31 5037 5037 5555/5554 5585/5584 5557/5556
  • 5. UI/Application Exercise Monkey The Monkey: generates pseudo-random streams of user events Application: stress-test applications Detect application crashes or receives any sort of unhandled exception. ANR error. Basic usage: $ adb shell monkey [options] <event-count>  Sample: $ adb shell monkey -p your.package.name -v 500  Reference: http://developer.android.com/guide/developing/tools/monkey.html
  • 6. Dalvik Debug Monitor Server  2 ways to start DDMS:  Command line.  Show DDMS perspective in Eclipse.  Using:  Monitoring:  Viewing heap usage for a process.  Tracking memory allocation of objects.  Examining thread information.  Starting method profiling.  Using LogCat.  File operation  Work with emulator or device’s file system.  Emulating phone operations and location  Changing network state, speed, latency.  Spoofing calls or SMS text messages.  Setting the location of phone.  Process Management  Execute garbage collection  Interrupt process  Reference: http://developer.android.com/guide/developing/debugging/ddms.html
  • 7. adb logcat command Use to view & follow the content of system log’s buffer. Filter log output: Using filter expression: tag:priority … tag:priority Controll log output format: Using –v switch: brief, process, tag, thread, raw, time, long. Viewing Alternative Log Buffers : Using –b switch: radio, event, main. Viewing stdout and stderr: setprop log.redirect-stdio true or edit /data/local.prop Reference: http://developer.android.com/guide/developing/tools/adb.html
  • 8. Device DDMS & Debuggers DDMS adb Connect VM monitoring service VM JDWP Debugger (jdb) VM start/stop adbd VM’s PID Monitor 8700 8600
  • 9. Hierarchy Viewer & layoutopt Purpose: Debugging & profiling user interface Tools: Hierarchy Viewer. layoutopt Reference: http://developer.android.com/guide/developing/debugging/debugging-ui.html
  • 10. Hierarchy Viewer Purpose: Debugging &optimize user interface Running HV: Connect your device or launch an emulator. Install the application you want to work with. Run the application, and ensure that its UI is visible. Launch hierarchyviewer The first window you see displays a list of devices and emulators. Select the name of your Activity from the list. You can now look at its view hierarchy using the View Hierarchy window, or look at a magnified image of the UI using the Pixel Perfect window
  • 13. layoutopt Purpose: analyze XML layout file to find inefficiences. Running layoutopt: layoutopt <xmlfile> Information display when effect is detected: The filename  The line number.  The description.
  • 14. TraceView & Method Profiling  TraceView: a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code.  Application:  Method profiling to find the bottle neck in your code execution.  Usage:  Create trace file:  Using Debug class: // start tracing to "/sdcard/xml.trace" Debug.startMethodTracing(“xml"); //Call to the method you want to trace. // stop tracing Debug.stopMethodTracing();  Using method profiling feature of DDMS to generate trace file.  Copy file to host machine.  Viewing trace file in Traceview.  Limitation:  Thread name is not emitted if thread exits during profiling.  Reuses thread ID of VM.  Reference: http://developer.android.com/guide/developing/debugging/debugging-tracing.html
  • 15. TraceView & Method Profiling  Timeline Panel:  Profile Panel:
  • 16. dmtracedump  Generate graphical call-stack diagram from trace log file. Call reference number Inclusive elapsed time Exclusive elapsed time Number of calls dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name>
  • 17. jhat & Heap Profiling  Heap Profiling helps to find the leak memory, speed up the program:  How many instances of a class.  How much memory usage.  Usage:  Set the break point:  Exception break point.  Conditional break point.  Dump HPROF file from DDMS.  Using jhat (java heap analysis tool) to parse hprof file.  Open the favorite web browser and visit: http://localhost:7000
  • 18. jhat & Heap Profiling  Exception breakpoint:  Run > Add Java Exception Breakpoint …  Conditional breakpoint:  Right click on breakpoint > Properties > Check Conditional checkbox > Enter the condition. Read more about MAT: http://10.1.6.46/mediawiki/index.php/Dectect_memory_leak_using_MAT
  • 19. jhat & Heap Profiling  Using DDMS dump hprof file:  Click on “Show heap histogram”:
  • 20. ANR & StrictMode  ANR.  Causes  Activity  BroadcastReceiver  StrictMode: public void onCreate() { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(); }  Reference: http://developer.android.com/guide/practices/design/responsiveness.html
  • 21. Dev Tools Application  Get it from emulator & install into real device.  Application:  Enable some settings in your device for testing & debugging.  Usage:  Launch it > Development Settings  Debug app  Wait for debugger  Show screen updates  Immediately destroy activities  Show CPU usage  Show background  Reference: http://developer.android.com/guide/developing/debugging/debugging-devtools.html
  • 22. Debug Tips  Dump the stack trace: adb shell > ps > kill -3  Display useful info on the emulator screen: View Dev Tools App  Get application and system state information from the emulator: View dumpsys and dumpstate  Get wireless connectivity information: DDMS > Device menu > Dump radio state  Log trace data: Call startMethodTracing()  Log radio data: adb shell>logcat –b radio  Capture screenshots: DDMS> Select device >Screen Capture  Use debugging helper classes: Log, Debug, StrictMode  Garbage collection: Any object the debugger is aware of is not garbage collected until after the debugger disconnects
  • 23. Nguyen Huu Phuoc, MEng. ●  Blog:http://folami.nghelong.com ●  Website http://phuocnh.nghelong.com