How to resolve ANR issue in the Android System (2024)

How do we debug and analyse ANR issues and what are some methods to resolve them?

How to resolve ANR issue in the Android System (3)

ANR is a common issue in Android but the resolution of an ANR can be a complex task. Like any other issue, the basic strategy to resolve the ANR issue is also the same. This article does not just focus on a single Application ANR resolution strategy. In contrast, here we are discussing Android system-based ANRs that can be raised in any layer of Android OS.

ANR detecting, debugging, and fixing the issue can be complex sometimes. I have already explained, What is ANR and its types and the ANR prevention strategies in the below articles, It is good to spare some time and read it for a better understanding.

Please have a look at these articles to understand what are ANR and Its prevention strategies →
What is ANR and Its Types → click here
How to Prevent ANR → click here

ANR as an issue is not like a generic crash which occurs by a programming language Errors or Runtime Exceptions. ANR comes on running system with Application not Responding Dialogue, where the user will have two options either wait for recovery or close the current Application.

“So it is obvious that ANR directly impacts User Experiences”

First of all, before understanding the strategies for solving the ANR issue, let’s create the ANR within an Android application and see the behaviour. It may help to understand better but it’s optional now!! on your choice!!

Create a simple Android Project in Android Studio and add one text field to the main Activity XML.

Add onTouchEvent Method and update the text field infinitely on the UI Thread which will cause an ANR for sure.

@Override
public boolean onTouchEvent(MotionEvent event) {
while(true) {
String s = new String("ABC");
text.setText(s);
}
}

Once you understand the ANR and ANR dialogue It will be more clear what issue we are solving.

First of all, we are very well aware that, ANR mean something is wrong like resource Resource-Intensive tasks happening on the UI thread.

So it is obvious!! what needs to be done.

Find out which process is responsible.

Find out which module class or component is responsible.

Find out which code segment is responsible.

Fix it!!

To find out the culprit process, there is no hard and forward approach available. so anyhow possible, you can find it. I am specifying a few approaches which are good in principle to use.

Visualize the ANR if possible

First Step!! If possible to recreate the issue we should recreate it and visualize it in the real situation.

During the recreation of the issue, we can probably directly hit the actual component which is causing the issue and then the next task is just finding the code segment, which may be responsible for the issue.

The above conditions will not be true for all kinds of Android development, it is possible that in some Android systems, the ANR dialog is disabled or Android is running on the device where the display is not available. Mostly possible in Android Automotive development in vehicles. So, the above approach 100% will only work for Android Phone devices. then go ahead with the next approach.

Review the logcat logs

Finding the ANR in the Logcat logs is simple!! Just need to look for some specific tags.

If you are not sure that ANR is suspected you can search Tag: “Dumping To” in the adb logcat logs, These logs will be available if the System stores the ANR traces.

Also in the case of ANR different system configuration processes which is affected by ANR can crash, die, or show the ANR dialog etc.

For Example! The process may die or WIN DEATH

WindowManager: WIN DEATH: 
Window{956ba12 u0 com.example.anrexample/com.example.anrexample.MainActivity}

W InputManager-JNI:
Input channel object '956ba12 com.example.anrexample/com.example.anrexample.MainActivity
(client)' was disposed without first being removed with the input manager!

I ActivityManager: Process com.example.anrexample (pid 1026) has died: fg TOP
I am_proc_died: [0,1026,com.example.anrexample,0,2]
I Zygote : Process 1026 exited due to signal 9 (Killed)

I libprocessgroup: Successfully killed process cgroup uid 10163 pid 1026 in 0ms

If the ANR is related to the InputDispatcher type ANR you can see the following logs.
Use Case: User input not working, leggy User Interaction or Application crash.


I input_focus: [Requesting to set focus to null
window,reason=UpdateInputWindows]
I am_uid_stopped: 10163

W ActivityTaskManager:
Force removing ActivityRecord{8c4f4bd u0 com.example.anrexample/.MainActivity} t72}: app died, no saved state

I wm_finish_activity: [0,147125437,72,com.example.anrexample/.MainActivity,
proc died without state saved]

I wm_task_removed: [72,removeChild:removeChild last
r=ActivityRecord{8c4f4bd u0 com.example.anrexample/.MainActivity} t-1 f}}
in t=Task{9dafe75 #72 type=standard A=10163:com.example.anrexample}]

I wm_task_removed: [72,removeChild]

W InputDispatcher: Focused display #2 does not have a focused window.
E InputDispatcher: But another display has a focused window
E InputDispatcher: FocusedWindows:
E InputDispatcher: displayId=0,
name='956ba12 com.example.anrexample/com.example.anrexample.MainActivity'

There might be several logs concerning different types of ANR, The above traces belong to InputDispatcher ANR Type.

Review The ANR Traces

As mentioned above the system dumps the ANR traces which will be stored in the particular location in the system. Reviewing the ANR traces can also help us on reaching to the component of the process which is causing the ANR.
Where ANR Traces Stored:

$ adb shell
$ cd /data/anr/

// ANR traces are located here
emu64xa:/data/anr # ls
anr_2023-12-14-19-28-32-538 anr_2023-12-14-19-29-36-151 anr_2023-12-14-20-00-45-326 anr_2023-12-14-20-13-14-457
anr_2023-12-14-19-28-44-334 anr_2023-12-14-19-31-44-384 anr_2023-12-14-20-12-08-414 anr_2023-12-14-20-14-36-388

Pull ANR traces:

$ adb pull /data/anr/anr_2023-12-14-20-14-36-388

output:
/data/anr/anr_2023-12-14-20-14-36-388: 1 file pulled, 0 skipped. 38.9 MB/s (908887 bytes in 0.022s)

What to look for in ANR Traces:
As you can see below, the “Subject” hints about the process that may be causing ANR.

Subject: 
Input dispatching timed out
(4ede5c7 com.example.anrexample/com.example.anrexample.MainActivity
(server) is not responding.

Waited 5007ms for MotionEvent(deviceId=8, eventTime=2817951084000,
source=TOUCHSCREEN | STYLUS, displayId=0, action=DOWN,
actionButton=0x00000000, flags=0x00000000, metaState=0x00000000,
buttonState=0x00000000, classification=NONE, edgeFlags=0x00000000,
xPrecision=30.3, yPrecision=14.0, xCursorPosition=nan,
yCursorPosition=nan, pointers=[0: (628.0, 680.0)]),
policyFlags=0x62000000)

The subject in ANR traces provided a direct hint about the component that caused ANR, but finding the exact root cause required more effort.

Find "waiting to lock", Find monitor state "Binder Thread #17" 
prio=10 tid=XXX MONITOR

Waiting to lock <0xblahblah> (com.example.anrexample) held by threadid=XXX
// tid=XXX" holds a task now. So go to tid=XXX, tid=XXX maybe SUSPENDED state
Which Class or Component!!

“Waiting to lock” will provide direct hind about the component which is causing the ANR but it is not true for always, you will get the traces of “waiting to lock” or “hold the lock”.

ANR come for multiple reasons and one of the reasons is deadlock conditions.

The “suspended” and “monitor-state” indicate which thread is being suspected and the suspended state of the thread is probably the main reason for the deadlock.

Logs Example!!

suspend all histogram: Sum: 18.016ms 99% C.I. 12us-1115.199us Avg: 52.832us Max: 2142us
DALVIK THREADS (18):
"main" prio=5 tid=1 Runnable
| group="main" sCount=0 ucsCount=0 flags=0 obj=0x73267fb8 self=0x792681817010
| sysTid=9435 nice=-10 cgrp=top-app sched=0/0 handle=0x7927d04bc4f8
| state=R schedstat=( 5919101120 249911838 1759 ) utm=529 stm=62 core=1 HZ=100
| stack=0x7ffc9f802000-0x7ffc9f804000 stackSize=8188KB
| held mutexes= "mutator lock"(shared held)
native: #00 pc 000000000071ed04 /apex/com.android.art/lib64/libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, int, BacktraceMap*, char const*, art::ArtMethod*, void*, bool)+132) (BuildId: 44bc52550248fc712a381bef164b75c7)
native: #01 pc 0000000000842dfe /apex/com.android.art/lib64/libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, bool, BacktraceMap*, bool) const+334) (BuildId: 44bc52550248fc712a381bef164b75c7)
native: #02 pc 0000000000862cf8 /apex/com.android.art/lib64/libart.so (art::DumpCheckpoint::Run(art::Thread*)+1256) (BuildId: 44bc52550248fc712a381bef164b75c7)
native: #03 pc 0000000000843e25 /apex/com.android.art/lib64/libart.so (art::Thread::RunCheckpointFunction()+181) (BuildId: 44bc52550248fc712a381bef164b75c7)
native: #04 pc 00000000009119d2 /apex/com.android.art/lib64/libart.so (artTestSuspendFromCode+34) (BuildId: 44bc52550248fc712a381bef164b75c7)
native: #05 pc 000000000037bb1d /apex/com.android.art/lib64/libart.so (art_quick_test_suspend+173) (BuildId: 44bc52550248fc712a381bef164b75c7)
at java.lang.StringFactory.newStringFromString(Native method)
at com.example.anrexample.MainActivity.onTouchEvent(MainActivity.java:39)
at android.app.Activity.dispatchTouchEvent(Activity.java:4266)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWr
apper.java:70)

Check Input Dumps

The Input Dispatcher as an input framework component takes care of sending input events to the Android Process. In the case of input-related ANRs, we also can see the input dumps which can provide us the information about ANR.

In the current ANR scenarios when ANR occurs I collected input dumps showing the ANR Reason below.

adb shell dumpsys input > input_dumps.txt

ANR reason logs from the input_dumps.txt file.

 Line 1408: Input Dispatcher State at time of last ANR:
Line 1409: ANR:
Line 1411: Reason: 5b492f7
com.example.anrexample/com.example.anrexample.MainActivity

(server) is not responding. Waited 5005ms for MotionEvent(deviceId=8,
eventTime=70280437729000, source=TOUCHSCREEN | S
TYLUS, displayId=0, action=DOWN, actionButton=0x00000000,
flags=0x00000000, metaState=0x00000000, buttonState=0x00000000,
classification=NONE, edgeFlags=0x00000000, xPrecision=30.3,
yPrecision=14.0, xCursorPosition=nan, yCursorPosition=nan,
pointers=[0: (560.0, 1227.9)]), policyFlags=0x62000000

Line 1412: Window:
ActivityRecord{e4c2074 u0 com.example.anrexample/.MainActivity} t83} -
5b492f7 com.example.anrexample/com.example.anrexample.MainActivity

Line 1418: displayId=0, name='ActivityRecord{e4c2074 u0 com.example.anrexample/.MainActivity} t83}',
dispatchingTimeout=5000ms

Line 1420: displayId=0,
name='5b492f7 com.example.anrexample/com.example.anrexample.MainActivity'

Line 1422: displayId=0,
name='5b492f7 com.example.anrexample/com.example.anrexample.MainActivity' result='OK'

Line 1441: 4: name='5b492f7 com.example.anrexample/com.example.anrexample.MainActivity', id=783, displayId=0, inputConfig=0x0, alpha=1.00, frame=[0,0][1080,2340], globalScale=1.000000, applicationInfo.name=ActivityRecord{e4c2074 u0 com.example.anrexample/.MainActivity} t83}, applicationInfo.token=0x7925618e8010, touchableRegion=[0,0][1080,2340], ownerPid=18130, ownerUid=10163, dispatchingTimeout=5000ms, hasToken=true, touchOcclusionMode=BLOCK_UNTRUSTED
Line 1443: 5: name='d2bfdf3 ActivityRecordInputSink com.example.anrexample/.MainActivity', id=780, displayId=0, inputConfig=NO_INPUT_CHANNEL | NOT_FOCUSABLE, alpha=1.00, frame=[0,0][0,0], globalScale=0.000000, applicationInfo.name=, applicationInfo.token=<null>, touchableRegion=[-10799,-23399][10800,23400], ownerPid=631, ownerUid=1000, dispatchingTimeout=0ms, hasToken=false, touchOcclusionMode=BLOCK_UNTRUSTED
Line 1486: 574: channelName='5b492f7 com.example.anrexample/com.example.anrexample.MainActivity (server)', windowName='5b492f7 com.example.anrexample/com.example.anrexample.MainActivity (server)', status=NORMAL, monitor=false, responsive=false

The above logs indicate that the InputDispatcher State at the time of the last ANR. For Process: com.example.anrexample /...MainActivity
(server) is not responding. Waited 5005ms.

Once we have suspected or found any process which might cause the ANR, then finding the code segment is more of a code walkthrough of the particular module or class.

Identify Long-Running Operations, Resource Intensive Tasks, Images Processing, Database Operation, RX Object subscription, Network Calls on the Main thread and possibly many more.

As per Android guidelines to Fix or Reduce the ANR, the following points are required to be investigated.

Remove the Slow code on the Main thread.

Should not do IO operations on the Main thread.

Carefully implement Lock contention.

Carefully Prevent Deadlocks.

Prevent writing Slow broadcast receivers.

If we have any suspected code written falling under the above category then look for that or as I defined above, In principle we need to look for a resource-intensive or a long-running task executing on the main thread of a process as the next task.

Concerning the finding culprit code segment this is more or less enough because It can be anything resource-intensive on UI Thread so the problem will be always specific to the functionality of the module in the software.

Conclusion!!

Fixing ANR is always a challenging task and sometimes becomes more difficult when the traces and logs do not provide enough information.
When it comes to system-level performance optimization, it is mostly difficult to optimize it in the later stage of development.

So this best practice is that we apply all the best practices including programming standards, catalytic, StrictMode, etc from the start itself so that we face fewer issues later stage.

There are tools recommended which are awesome for analyzing the application performance like Janky Frame, UI Transitions, and Memory Leak using Android Profiler and Sys Traces. Same for ANR we have a few tools like Strict Mode and ANR Watchdog Libraries which can help to reduce the ANR and also detect the ANR.

How to resolve ANR issue in the Android System (4)

Thanks for Reading!

Please comment with questions and suggestions!! If this blog is helpful for you then hit Please hit the clap! Follow on Medium, Connect on LinkedIn, Follow on Insta and send emails if any discussion is needed on the same topic on copy email.
Please Follow & subscribe to Make Android Publication by Narendra K H for prompt updates on Android platform-related blogs.

Thank you!

Make AndroidMake Android your writing space into the world of Android. Uncover the future of technology through our in-depth…medium.com

Thanks To!! Android-World, Head First Android, Android Dev Notes, TUDO ANDROID, The Android Developer, The Funtasty Android Devs, @Nikhil, Abhishek Pathak, Android Developers, Betul Necanli.

How to resolve ANR issue in the Android System (2024)
Top Articles
'Little Giants': 25 things we love about the classic pee-wee football movie | Sporting News
Warrant Search Fort Smith Ar
Great Clips Mount Airy Nc
Umbc Baseball Camp
Form V/Legends
Cash4Life Maryland Winning Numbers
Mate Me If You May Sapir Englard Pdf
Cad Calls Meriden Ct
Rabbits Foot Osrs
Craigslist Mexico Cancun
The Best English Movie Theaters In Germany [Ultimate Guide]
Call of Duty: NEXT Event Intel, How to Watch, and Tune In Rewards
Savage X Fenty Wiki
Pwc Transparency Report
Craigslist Jobs Phoenix
Slope Unblocked Minecraft Game
Hmr Properties
The Shoppes At Zion Directory
Lima Funeral Home Bristol Ri Obituaries
Munich residents spend the most online for food
How pharmacies can help
White Pages Corpus Christi
Yisd Home Access Center
12 Facts About John J. McCloy: The 20th Century’s Most Powerful American?
Divina Rapsing
Dmv In Anoka
Walgreens On Bingle And Long Point
FAQ's - KidCheck
Restaurants In Shelby Montana
Robotization Deviantart
Umn Biology
Where to eat: the 50 best restaurants in Freiburg im Breisgau
49S Results Coral
Plasma Donation Racine Wi
Wega Kit Filtros Fiat Cronos Argo 1.8 E-torq + Aceite 5w30 5l
Roch Hodech Nissan 2023
RUB MASSAGE AUSTIN
Car Crash On 5 Freeway Today
Arcane Odyssey Stat Reset Potion
RALEY MEDICAL | Oklahoma Department of Rehabilitation Services
Bella Thorne Bikini Uncensored
Reese Witherspoon Wiki
Gfs Ordering Online
Firestone Batteries Prices
Electric Toothbrush Feature Crossword
Chase Bank Zip Code
Portal Pacjenta LUX MED
Rescare Training Online
Lebron James Name Soundalikes
Brutus Bites Back Answer Key
Raley Scrubs - Midtown
Metra Union Pacific West Schedule
Latest Posts
Article information

Author: Arline Emard IV

Last Updated:

Views: 6220

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Arline Emard IV

Birthday: 1996-07-10

Address: 8912 Hintz Shore, West Louie, AZ 69363-0747

Phone: +13454700762376

Job: Administration Technician

Hobby: Paintball, Horseback riding, Cycling, Running, Macrame, Playing musical instruments, Soapmaking

Introduction: My name is Arline Emard IV, I am a cheerful, gorgeous, colorful, joyous, excited, super, inquisitive person who loves writing and wants to share my knowledge and understanding with you.