PS: Ok, don’t baidu, catch shrimp is “initial D” a soundtrack “Deja Vu”, Chinese homophone “catch shrimp household”, racing drift special BGM, sometimes the music also implies: drive.

This section is not about driving, of course, but about debugging, a cliche of Android development.

A developer’s daily life is inseparable from: BUG writing and BUG solving, especially when multiple people collaborate, it is common to help others wipe their asses (BUG solving). In addition, taking over other people’s projects and working on bugs can help you get started quickly. To sum up, it is particularly important to cultivate the skill of “debugging”. But, but it feels like a lot of players are still stuck in the mindless printing stage, so there is this article.

I’ve done my best to walk through the qi and JI aspects of Android debugging in the most streamlined way possible.

To catch shrimp


1. Mindless static debugging

Explain the title:

  • Brainless: Print where you think there is a problem.
  • Static: Every time you want to print, you have to modify the code and re-run the program.

For: Want to see if the value of a variable is abnormal at some point!

Here are two common debugging methods:

Toast to print method

Novice Android developer favorite debugging method, easy to use, just a line of code, easy to print:

Toast.maketext (mainactivity.this, "Toast debugging ", toast.length_short).show();Copy the code

Convenience is convenient, but there is one caveat: after Android 5.0, if you turn off the “message notification privilege”, some phones will not display Toast! You can also use Snackbar to display values for debugging:

Snackbar. Make (parent view, "Snackbar debug ", snackbar.length_short).show();Copy the code

Or another workaround, such as adding a TextView to the page that displays the value directly in the text box.

Log Indicates the Log printing method

Toast debugging is cool, but there are two problems:

  • 1. If you want to debug and print multiple values, Toast will pop endlessly. After all, only “one” Toast is displayed in the foreground at any one time.
  • 2. Toasts disappear after a certain interval, even if you set toast. LENGTH_LONG;

Maybe as soon as you’re distracted, Toast disappears before you have a chance to look at the debugged values. We really need a way to print logs without worrying about debugging results. This is to print logs to the Logcat console using the Android system’s Log class.

Log.d("TAG", "Log debug ")Copy the code

When the code executes to this line, the debug information will be printed in the Logcat console. In addition, Logcat will print all log information by default. We can do some filtering to locate the debug log information. The first is log type. Android supports six log types, as follows:

  • Verbose: indicates detailed log information of all types.
  • Debug: logs used for debugging.
  • Info: indicates logs that need to be paid attention to in normal use.
  • Warn: Logs that Warn that problems may occur but no errors occur.
  • Error: indicates the log information about serious errors during running.
  • It’s an Assert.

Tips:

Do not enter the Error level, I used to type Log all Log. E, the reason is that the Log information is red, beautiful… O (TωT) O, think the color is not good, you can follow the following operation to customize.

Open “Settings” – “Editor” – “Colors Scheme” – “Android Logcat” to select the log type, then uncheck it and click Select Color color value

Here is the author’s color scheme, readers can adjust to their favorite color:

  • Assert: 8 f0005
  • The Debug: 0070 bb
  • Error: FF0006
  • Info: 48 bb31
  • Verbose: BBBBBB
  • Warning: BBBB23

The color matching after setting is as shown in the figure:

Ok, you can debug and customize the Logcat color scheme using the Log class, and also mention the “Log filtering” posture.

  • Customize the log Header display content: Click Logcat Header on the panel to set the log Header information

The optional Settings are as follows:

You can also filter Log information to support regex on the right, and filter specific logs on the right.

If that’s not enough, click Edit Filter Configuration on the far right to configure a Filter of your own.

Alternatively, you can perform a “log search” by clicking on the Logcat center area to get focus, Ctrl + F to bring up the search toolbar, and then search for the relevant log content.

By the way, I’ll mention an easy to overlook bug in the Log class:

The Log class will only print 4000 characters, not more than that!!

2. Dynamic brain debugging method

In fact, it is to use the Debug mode provided by Android Studio to Debug the program. Compared with the previous Toast printing and Log printing methods, it is a little more complicated. There are some learning costs, and it requires a lot of thinking. Let me show you nine shallow one deep, em… Learn the basics of Android Studio Debug.

1) Basic debugging process

The general debugging flow chart is as follows :(the core is the breakpoint, single step debugging, value tracking)

2) Break point

First talk about breakpoint, not Zhang Jingxuan “breakpoint”, debugging the role of breakpoint is:

When the program executes to the code where the breakpoint is, the application is suspended, the thread is suspended, and can then be traced through the debugger.

The breakpoint is also simple: click on the left side of a line of code, and a small red dot appears as shown.

The little red dot is a breakpoint, and in AS, there are several types of breakpoints. Let me walk you through them:

  • 1) line breakpoints

This is used to debug a particular row by clicking on the left sidebar of the row. Right-click on the breakpoint and the Settings dialog will appear as follows:

If you uncheck Enabled, the breakpoint is disabled as shown below:

  • ② Method breakpoint

If you place a breakpoint in front of a method, it looks like this:

This is a method breakpoint, which is used to check the input parameters and return values of a method.

  • ③ Variable breakpoint

Sometimes we don’t care about how the program is running, but only how a variable is changing. We can add a breakpoint before the variable definition.

In the process of running the program, if the value of the variable changes, the program will automatically stop and locate the variable value changes for the developer to debug.

In addition, you can also set breakpoints by right-clicking. The Watch panel has two unique options that can be checked as needed:

  • Field Access: A breakpoint is triggered when a Field is accessed.
  • Field modification: Breakpoints are triggered when a Field is modified.
  • ④ Conditional breakpoint (breakpoint setting Condition)

Sometimes there is a scenario where we hit a breakpoint into the body of a loop, and we only care about what happens at a certain number of loops. For example, if we have a loop that runs 10 times, we want to know what happens at the eighth time of the loop. If you don’t know the conditional breakpoint, you need to press “Run to Cursor” until our condition is met. For example:

We want to know what sum is when I is equal to 8, so you just keep pressing Run to Cursor.

Press 7 times until I = 9. If a conditional breakpoint is used, the loop body will stop when it reaches a condition. Right-click the breakpoint and enter the equation condition as shown in the figure below:

And then you can see that the program just jumps to I =8 and then suspends, which is very convenient.

  • ⑤ Log breakpoints

During debugging, we can print logs to locate the approximate location of abnormal code to narrow the scope of the problem, and then use breakpoints to locate the problem precisely. If it is a normal print log, we need to wait to rebuild the program. If we use “log breakpoint”, we avoid this meaningless wait. Using a log breakpoint is very simple. Right-click a breakpoint and uncheck “Suspend”. A pop-up window like the one shown below appears, and select “Evaluate and log” to enter the desired output.

After running the debug, you can see the console output the corresponding log information when the log breakpoint is executed, and the program is running normally and does not hang.

If you want to see more detailed information, such as the location of the breakpoint and the stack information when it is triggered, check the boxes “Breakpint hit” message “and” Stacktrace “to make the output more detailed:

  • ⑥ Temporary breakpoint

Temporary breakpoints are breakpoints that are triggered once and then automatically deleted. There are two ways to set this:

  • 1. Move the cursor to the Line you want to click and click the menu bar “Run” -> “Toggle Temporary Line Breakpoint”.

Equivalent to shortcut keys: “Ctrl+Alt+Shift+F8”

  • 2. Easier operation: Hold down Alt and click the left sidebar.

To Remove temporary breakpoints, deselect Remove once Hit to change temporary breakpoints to normal breakpoints.

  • ⑦ Abnormal breakpoint

Used to listen for program exceptions, once the program crashes, directly locate the exact location of the exception. Click “Run” -> “View Breakpoints” to open the Breakpoints View. Click “+”, then select “Java Exception Breakpoints”, and enter the Exception to debug in the window that pops up:

In addition to setting exception breakpoints, you can see all breakpoints set by the project, manage and configure breakpoints. In addition, you can also set custom Exception Breakpoints, click “4.Exception Breakpoints” to configure yourself.


3) Another way to get into debug mode

Most students debug by clicking on the bug below to go into debug mode.

One disadvantage of this approach is that you need to re-run the APP every time. You might throw the APP to a test, and a rare BUG appears. If you use normal Debug mode, you need to restart the APP, but the BUG may not reappear, which is embarrassing. For scenarios that require dynamic debugging, you can “directly debug running Android processes” by clicking on another icon with bugs as shown below:

Then select the name of the package to debug, you can debug the application directly without restarting it:


4) Debug tool details

Here, the debugging tool is divided into five areas as shown in the figure:

  • Zone A (Step debugging tool)
icon The name of the Functional description
Show execution points Locate the breakpoint currently being debugged.
Single step over Step by step execution, encountered method directly execute method, enter the next step, will not enter the method inside.
Step into the Step by step, method encountered andCustom methodsOtherwise, the method is not entered.
Forced into Methods encountered, whether custom or official libraries, will be inside the method.
Step out of Jump out of the currently entered method and return to the next line at the method call (which also means the method has been executed).
Discard the frame If you’re inside a method and you’re done discarding a frame, the current method is interrupted and returns the method that was called

The value of the variable is also reset.
Execute to cursor This can be considered a temporary breakpoint. The program pauses at the current cursor line.
Computed expression During debugging, you can modify the value of any variable through assignment or expression.

!!!!!!!!! Note: There is no breakpoint between the Cursor and the Cursor. If you want to Force the Cursor to the Cursor, you need to “Force Run to Cursor”. You can do this in either of the following ways:

  • 1. Right-click the Cursor and select “Force Run to Cursor”, as shown in the figure:

  • 2. Press the shortcut keys Ctrl + Alt + F9.

Evaluate Expression

Very practical, you can dynamically view and modify the value of any variable, in addition to the above in the debug window click on the calculator icon can be opened,

You can right-click a variable in the D area to open it. To demonstrate how to change the value of a variable:

After modifying it, click Evaluate and the result is as follows:

You can also view the value of a variable directly here, as shown in the following example:

Click on the sameEvaluate, the results are as follows:

  • Zone B (Control debugging tools)
icon The name of the Functional description
Continue program run It runs to a breakpoint and pauses, and if there’s another breakpoint, it clicks and jumps to that breakpoint,

If not, the program continues to run.
Pause the program Pause the program.
Abort program execution Terminate the program.
Check the breakpoint You can view all breakpoints, manage and configure breakpoints
Disable all breakpoints Toggles the state of all breakpoints (enabled/disabled). When disabled, breakpoints will not be triggered.
Get the thread stack Displays information about threads
Restore the layout Restore to original layout
Set up the Debugging related configurations, such as whether to display the return value after executing a method
  • Zone C (Frame debugging window)

Frames are: stack frames, a data structure used to “store data” and “partial process results”; Each call to a method takes up a portion of memory on the stack, in frames, that are created as the method is called. Each stack frame contains “incoming parameters,” “return address,” “local variables,” and “information to support program debugging.” A thread consists of multiple stack frames.

In the view tool, you can view frames by switching from top to bottom (click the mouse directly), and the funnel icon on the right can be filtered out after clicking: “frames not of this application”. Alternatively, you can right-click the stack frame and add a “step filter”, “Export thread” or “Custom thread display”.

  • Area D (variable area)

In this area you can see all the current data (method parameters, local variables, instance variables) in the stack frame. Right-click a variable to “set \ copy variable value”, “jump to variable location in the code” and so on. A common action: select ** “Add to Watches” ** to monitor this variable separately.

  • Area E (Monitoring window)

In addition to the previous method of right-clicking to add monitoring, you can also add it directly by clicking “+” in the E area.

You can monitor not only variables, but also expressions, such as I +1 above. About the basic operation of Android Debug about these, more to the actual combat experience to consolidate it!


3.Android Wifi wireless debugging

It is also very easy to install the “ADB WIFI” plug-in on your computer and restart it:

And I’m gonna debug my APP in Usb Device mode.

Connect the phone TO the computer, click the menu bar of AS successively: “Tools” -> “ADB USB TO WIFI”, and then the lower left corner will appear:

Generally speaking, it takes a long time to scan. It is recommended to look at the phone’S IP and link to it through adb command, as shown in the following example:

Adb connect 10.1.7.200:5555 adb connect 10.1.7.200:5555Copy the code

After the connection is successful, you can unplug the data line for wireless debugging.


4. Use Network Profiler to capture packets

Android Profiler is a performance analysis tool introduced after AS 3.0, and Network Profiler is one of the tools used for Network analysis. By using it, we can directly capture packets without using third-party packet capture tools (such AS Charles) for analysis and debugging. Relatively simple, the interface is as follows:

It can be used to capture packets conveniently.


There’s more to Android debugging than that, of course, but these are the basics. For more debugging tips, please leave a comment in the comments section. Thank you


References:

  • Debugging tips in Android Studio
  • Android Studio Breakpoint Debugging 3 (In Depth)

PS: the last article has a child shoes in the comment area message said in the small column to see the same article, the author is actually me, column payment, generally can not put out the paid article for free, but feel the article is very useful to many Android developers, so I put out the nuggets. Currently writing, less content, will not make public, Android entry to the tutorial: beginners can learn Android system, in hand can check the gaps to consolidate the foundation. (/ω \) Of course, if you think this article is very helpful to you, you can also buy this article under the porcelain pig, hehe ~