问题
When my Android app fails to run as expected, how do I figure out what causes the problem? What tools are available for specifically debugging Android apps?
(I am writing this Q&A to gather information from several pages in the Android documentation all into one place.)
回答1:
logcat
logcat is one of the most useful tools for debugging Android apps. Commonly a buggy app terminates with a message that states "Unfortunately, has stopped." To find out the cause, you can get a stack trace with the logcat
tool.
logcat
is also a useful tool for general debugging. Android does not have a console, so the typical System.out.println()
calls are not very helpful to print out tracing information and values of variables. Instead, you can use the android.util.Log class (see also Reading and Writing Logs in the Android documentation). This class provides functions to output logging message with 5 levels of severity: ERROR, WARN, INFO, DEBUG, VERBOSE. Each level of severity has a corresponding method, so you rarely use these constants explicitly.
For debugging purposes, you will usually use Log.d()
which comes in two forms: Log.d(String, String) and Log.d(String, String, Throwable). The first String
paramter is a "tag" which can be anything you want. Often this is just the name of the class which is logging the message. This tag allows you to filter logging message with logcat
, so you can use it to quickly and easily find the messages that you care about. The second String
is the actual logging message. which can be a simply execution trace or the value of a variable or any other output that you find helpful for debugging purposes. The last parameter is an optional Throwable
which can be used, for example, to log an Exception in a throw...catch
statement.
Now once you have logging messages in your app, you can use logcat
to view them. The exact details of how to do this depend on whether you are developing with the command-line tools or with Eclipse and Android development plugin:
Command-line
The simplest form is to run
adb logcat
This is helpful if you only need to see the stacktrace when an your app throws an exception. If you want to filter out certain debugging messages, you can do this by the tag strings and logging levels you used. The syntax is
adb logcat <tag>:<debugging level> ...
For example, if I used the tag "HelloAndroid" when calling Log.d()
, I can type
adb logcat HelloAndroid:D *:S
(The *:S
at the end silences output for all other tags.)
Conclusion
Debugging is a crucial skill for any programmer, perhaps more important than learning to write code. I hope the above tips help decrease the learning curve for anyone diving into Android development. Hopefully you can get up to speed more quickly than I have.
来源:https://stackoverflow.com/questions/14298667/debugging-my-android-app