Detailed explanation of ANR usage

1c761c9fb8b73e3b2aed2888cd99a1ac.gif

Learn with you for lifeXi, this is Programmer Android

Recommended classic articles. By reading this article, you will gain the following knowledge points:

1. Overview of ANR
2. Types of ANR
3. Causes of ANR
4. How to analyze and solve ANR problems
5. ANR problem analysis and solution suggestions
6. Analysis of MTK platform ANR problems

1. Overview of ANR

In Android, application responses are monitored by Activity Managerand system services. , is a self-protection measure. When the main thread is stuck,  the system will give the user a pop-up prompt, allowing the user to manually choose to continue waiting or forcefully close the thread .Window ManagerANR(Application Not Responding )AndroidAndroidAPP

When Android detects one of the following situations, a dialog box Androidfor a specific application will be displayed ANR. The following three situations ANRwill often occur:

  • 1. UI ThreadMore than  5 sno response

  • 2. No response Broadcastafter broadcast exceeds10 s

  • 3. Service The service exceeds the limit  20s and does not respond.

Therefore, to avoid ANRthis happening, please do not perform time-consuming operations in the main thread. Please run time-consuming operations in child threads as much as possible.

  • 4. ANRThe screenshot of the occurrence is as follows:

0770a8df23c9aaf62163afc8228de19b.jpeg

ANR Dialog example

2. Types of ANR

ANRIt is very common in Android mobile phones and can be divided into the following three common types according to their corresponding types.

ANR types are as follows:

  1. The key response distribution timeout (Key Dispatch Timeout)
    is by default  5 s. If exceeded, ANR will occur.

  2. The broadcast timeout (Broadcast Timeout)
    is by default  10 s, if exceeded, ANR will occur.

  3. The service timeout (Service Timeout)
    is the default  20 s. If it exceeds, ANR will occur.

3. Causes of ANR

In Androidthe system, APP it usually runs in a UI Threador called MainThread. And Androidthere is only one MainThread sum in Main Message Queue. MainThreadMainly used UIfor drawing, event response, monitoring and receiving event processing and other functions. Main Message Queue A queue that mainly stores messages that users want to process. After the main thread gets the message MainThreadfrom the message queue , it distributes it as soon as possible. Once a certain message distribution times out, it may happen.Main Message QueueMessageANR

Therefore, when ANR it occurs, we need to analyze ANRthe cause, that is, find the reason why the message is not processed in time. For example, it can be analyzed from the following question points:

  • 1. Why  APPcan’t I get CPUthe time slice?

  • 2. APP Are you waiting for some events that cannot be processed in time to be completed?

  • 3. Is the message processing process too complicated?

4. How to analyze and solve ANR problems

ANRThere are some common patterns to choose from when analyzing :

  1. APPA slow I/Ooperation is taking place on the main thread.

  2. APPVery complex calculation operations are being performed in the main thread.

  3. The main thread is performing a synchronous program call to another process Binder, but the other process is taking a long time to return the results.

  4. The main thread is blocked while waiting for another child thread that is performing a long block operation.

  5. The main thread is deadlocked by another thread. Whether it is Binda call or a main thread call, the main thread cannot wait for a long time, let alone perform complex calculations in the main thread.

Knowing the causes of ANR, how to avoid ANR problems?

1.Strict mode

Using StrictModecan help you detect unexpected operations on the main thread while developing your application I / O. You can use applicationor .activityStrictMode

2. Close the ANR Dialog prompt

View methods controlled by method ANR:
Settings----Developer Options---显示所有ANR

Note:
If there is no developer option, please go to settings---about phone---click the version number multiple times to open the hidden developer option item

6b81a5b40a994f1c19026d3fb111cae9.jpeg

Background app ANR switch

3.Traceview

Traceview obtains the tracing information of the running application. By analyzing this traces.txtfile, you can infer that the main thread is busy with something.

tracesThe file is usually saved /data/anr/traces.txtunder , and you can adb cat view it directly or  adb pullexport it.

It is recommended to use this method

adb root 
 adb remount 
 adb pull /data/anr/traces.txt  .

7abe9d26e8fedb6116733321a32a8543.jpeg

pull traces file to desktop

5. ANR problem analysis and solution suggestions

Analyze to see ANRthe cause and then solve ANRthe problem.

1. Time-consuming operation

Please place it at the work site and it can be used Handler、AsyncTasketc.

2. IO operations

(For example: network operations, storage operations, etc.) are also common factors that cause ANR. It is highly recommended to do this in a worker thread.

3. Program lock competition

In some cases, ANRthe cause is not directly caused by the main thread. For example: the working thread 资源locks a certain wait, and the main thread needs it at this time 资源. If the wait times out, ANR may occur at this time.

4. Deadlock

ANRThis may occur when the main thread enters the wait state because it is requesting a resource that is being held by another thread .

5. Slow broadcast reception

Applications can respond to broadcast messages through broadcast receivers, such as enabling or disabling airplane mode or changing connection status. ANRIt can happen when an application takes too long to process a broadcast message, theoretically exceeding 10 seconds before processing is completed .

6. Broadcast ANR occurs under the following circumstances:

  1. onReceive() The method has not been executed for a long time.

Try to avoid onReceive() time-consuming operations in .

  1. The broadcast receiver called goAsync()a method and it failed PendingResultto be called on the object finish().

If there is a lot of broadcast content to be processed, please use IntentService .

For example:

3. It is not recommended to perform time-consuming operations in the onReceive method. If it is not processed for more than 10 seconds, it will cause ANR.

a9519a569ac88732d3ef222a17b96c42.jpeg

It is not recommended to perform time-consuming operations in the onReceive method. If it is not processed for more than 10 seconds, it will cause ANR.

  1. Recommended to use IntentService to avoid ANR occurrence

90729d1f3a034bd239ea3c512cfdaefd.jpeg

IntentService avoids ANR caused by processing too many broadcast messages

Your broadcast receiver can be used goAsync()to notify the system that more time is needed to process the message. However, you should PendingResultcall it on the object finish(). The following example shows how to call finish() to let the system recycle the broadcast receiver and avoid ANR:

aa89f5c8bf2cf1fbe455d8f88a27e4a1.jpeg

goAsync()---finish gets more broadcast response time

6. Analysis of ANR issues on MTK platform

Prerequisite, grab a ANRcopy MTK log.

1.event_log

Search keywords  am_anror anranalyze and see ANRthe reasons

7d56bcb4269c86db7740960a5ab3527c.jpeg

event_log analyzes the causes of ANR

2. main_log

Search for keywords Application Not Respondingor anr analyze and see ANRwhy.

6e000ff2a975b9b41f296188ef3b42e1.jpeg

Analyze ANR causes in main_log

3. MTK ANR strategy recommendations

2ed29b0faa8645738ca8d2779a2ea1df.jpeg

MTK official summary chart

ab3c78c0cecc7f22cb0e9bb1a46e1514.jpeg

MTK ANR analysis steps

eeead123ee48ac26bfaafb5b88d972fd.jpeg

MTK ANR Debug SOP

f8c289561a7f65dc43a89eb09f74d59c.jpeg

MTK ANR Debug SOP

4. Common ANR examples are analyzed as follows:

79c5c64105ade595fdd4daf12763a489.jpeg

Main Thread is idle

1fa8f3f0c2ea023112135de6ae1fd279.jpeg

Stuck in IO

66b410e64a32dbe40dd197bca15c06a2.jpeg

Main Thread Waiting a lock

e3afc14347f6c39dbb37969bddf3ea3d.jpeg

Wait Binder Transaction

6908d3b3803546862db78878b743acd6.jpeg

Main Thread Query DB

references:

[Tencent Documentation] Android Framework Knowledge Base
https://docs.qq.com/doc/DSXBmSG9VbEROUXF5

Friendly recommendation:

Collection of useful information on Android development

At this point, this article has ended. The editor thinks the article is reprinted from the Internet and is excellent. You are welcome to click to read the original article and support the original author. If there is any infringement, please contact the editor to delete it. Your suggestions and corrections are welcome. We look forward to your attention and thank you for reading, thank you!

2c27a71cc8be9710500c2efdfddd8298.jpeg

Click to read the original article and like the boss!

Guess you like

Origin blog.csdn.net/wjky2014/article/details/131874766