First, ANR introduction
On Android, if your application is unresponsive for a period of time, a dialog box is displayed to the user called the application unresponsive (anr:application not responding) dialog box. The user can select "Wait" and let the program continue to run, or "Force shutdown". So a smooth and reasonable application can not appear ANR, and let users each time to process this dialog box. Therefore, it is important to design the response performance in the program so that the system does not display ANR to the user. By default, the maximum execution time for an activity in Android is 5 seconds, and the maximum execution time for a broadcastreceiver is 10 seconds.
II: Types of ANR
There are generally three types of ANR:
1. Keydispatchtimeout (5 seconds)--Main type button or touch event no response at a specific time
2. Broadcasttimeout (seconds)--broadcastreceiver cannot be processed within a specified time
3. Servicetimeout (seconds)--The small probability type service cannot be completed within a specified time
Three: Keydispatchtimeout
Akey or touch event is not dispatched within the specified time (no response to keystrokes or touches events for a specific period)
The definition of the specific timeout period is Activitymanagerservice.java under the framework
How long we wait until we timeout on key dispatching.
staticfinal int key_dispatching_timeout = 5*1000
Four: Why is it timed out?
The timeout count is typically sent from the button to the app. There are generally two reasons for the timeout:
(1) The current event does not have a chance to be processed (i.e. UI line one thread in the previous event, not completed in time or Looper blocked for some reason)
(2) Current events are being processed, but not completed in time
five: How to avoid keydispatchtimeout
1. UI threads try to do only UI-related work
2. Time-consuming work (such as database operations, I/O, connection to the network, or any other action that may hinder the UI thread) put it into a separate thread processing
3. Try to use handler to deal with the interaction between Uithread and other thread
Six: UI Threads
With so many UI threads, which ones belong to the UI thread?
The main UI threads include the following:
1. Activity:oncreate (), Onresume (), OnDestroy (), OnKeyDown (), OnClick (), etc
2. Asynctask:onpreexecute (), Onprogressupdate (), OnPostExecute (), oncancel,etc
3. Mainthread handler:handlemessage (), post* (runnable R), etc
4. Other
Seven: How to analyze ANR
First look at the log:
04-01 13:12:11.572 I/inputdispatcher (): application is not responding:window{2b263310com.android.email/ Com.android.email.activity.splitscreenactivitypaused=false}.
5009.8ms since event, 5009.5ms since waitstarted
04-0113:12:11.572 I/windowmanager (): Input Event
Dispatching TimedOut sending
Tocom.android.email/com.android.email.activity.splitscreenactivity
04-01 13:12:14.123 i/process (): Sending signal. pid:21404 sig:3---Occurrence of ANR and time of generation of Trace.txt
04-01 13:12:14.123 I/DALVIKVM (21404): Threadid=4:reacting to
Signal 3
......
04-0113:12:15.872 E/activitymanager (): ANR in
Com.android.email (com.android.email/.activity. splitscreenactivity)
04-0113:12:15.872 E/activitymanager (220):
Reason:keydispatchingtimedout
04-0113:12:15.872 E/activitymanager (): load:8.68/8.37/8.53
04-0113:12:15.872 E/activitymanager (): CPUUsage from 4361ms to 699ms ago----CPU usage before ANR occurred
04-0113:12:15.872 E/activitymanager: 5.5%21404/com.android.email:1.3% user + 4.1% Kernel/faults:
Ten minor
04-0113:12:15.872 E/activitymanager (): 4.3%220/system_server:2.7% user + 1.5% kernel/faults:11
Minor 2 major
04-0113:12:15.872 E/activitymanager (): 0.9%52/spi_qsd.0:0% user + 0.9% kernel
04-0113:12:15.872 E/activitymanager (): 0.5%65/irq/170-cyttsp-: 0% user + 0.5% kernel
04-0113:12:15.872 E/activitymanager (): 0.5%296/com.android.systemui:0.5% user + 0% kernel
04-0113:12:15.872 E/activitymanager (): 100%total:4.8% user + 7.6% kernel + 87% iowait
04-0113:12:15.872 E/activitymanager (): CPUUsage CPU usage after 3697ms to 4223ms later:--ANR
04-0113:12:15.872 E/activitymanager (): 25%21404/com.android.email:25% user + 0% kernel/faults:191 minor
04-0113:12:15.872 E/activitymanager (): 16% 21603/__eas (par.hakan:16% user + 0% kernel
04-0113:12:15.872 E/activitymanager (): 7.2% 21406/gc:7.2% user + 0% kernel
04-0113:12:15.872 E/activitymanager (): 1.8% 21409/compiler:1.8% user + 0% kernel
04-0113:12:15.872 E/activitymanager (): 5.5%220/system_server:0% user + 5.5% kernel/faults:1 minor
04-0113:12:15.872 E/activitymanager (): 5.5% 263/inputdispatcher:0% user + 5.5% kernel
04-0113:12:15.872 E/activitymanager (): 32%total:28% user + 3.7% kernel
Log can see the type of ANR, CPU usage, if the CPU usage is close to 100%, indicating that the current device is busy, there may be CPU hunger caused by ANR
If the CPU usage is small, the main thread is blocked
If the iowait is high, it is possible that the main thread was caused by an I/O operation ANR
In addition to looking at log, to solve ANR still need trace.txt file,
How to get it? You can use the following command to obtain
$chmod 777/DATA/ANR
$RM/data/anr/traces.txt
$ps
$kill-3 PID
Adbpull Data/anr/traces.txt./mytraces.txt
From the Trace.txt file, see the most is the following information:
-----pid 21404 at 2011-04-01 13:12:14-----
Cmdline:com.android.email
Dalvik THREADS:
(mutexes:tll=0tsl=0 tscl=0 ghl=0 hwl=0 hwll=0)
"Main" prio=5 tid=1native
| group= "main" Scount=1 dscount=0obj=0x2aad2248 self=0xcf70
| systid=21404 nice=0 Sched=0/0cgrp=[fopen-error:2]
handle=1876218976
Atandroid.os.MessageQueue.nativePollOnce (Native method)
Atandroid.os.MessageQueue.next (messagequeue.java:119)
Atandroid.os.Looper.loop (looper.java:110)
At Android.app.ActivityThread.main (activitythread.java:3688)
At Java.lang.reflect.Method.invokeNative (Native method)
Atjava.lang.reflect.Method.invoke (method.java:507)
Atcom.android.internal.os.zygoteinit$methodandargscaller.run (zygoteinit.java:866)
At
Com.android.internal.os.ZygoteInit.main (zygoteinit.java:624)
At Dalvik.system.NativeStart.main (Native method)
Indicates that the main thread waits for the next message to enter the message queue
Eight: Thread State
ThreadState (defined at "Dalvik/vm/thread.h")
thread_undefined =-1,/* makes enum compatible with int32_t * *
Thread_zombie = 0,/* terminated * *
thread_running = 1,/* RUNNABLE or RUNNING now * *
thread_timed_wait = 2,/* timed_waiting in Object.wait () * *
Thread_monitor = 3,/* BLOCKED on a MONITOR * *
thread_wait = 4,/* Waiting in object.wait () * *
thread_initializing= 5,/* allocated, not yet running * *
thread_starting = 6,/* started, not yet on thread list * *
Thread_native = 7,/* out in a JNI NATIVE method * *
Thread_vmwait = 8,/* Waiting on a VM resource * *
thread_suspended = 9,/* suspended, usually by GC or debugger * *
Nine: How to investigate and solve ANR
1. First Analyze log
2. View call stack from Trace.txt file.
3. Look at the code
4. Take a closer look at the genesis of the ANR (Iowait?block?memoryleak?)
10: Cases
Case 1: Key words: Contentresolver in Asynctask onpostexecute, high iowait
Reason: Iowait is high, indicating that the current system is busy with I/O, so the database operation is blocked
Originally:
Final message Message=message.restoremessagewithid (Mprovidercontext,messageid);
if (message==null) {return
;
}
Account Account=account.restoreaccountwithid (Mprovidercontext,message.maccountkey);
if (account==null) {
Return;//ismessagingcontroller returns false for null, but let ' s make itclear.
}
if (Ismessagingcontroller) {
new Thread () {
@Override public
void Run () {
Mlegacycontroller.processpendingactions (Message.maccountkey);
}}.start ();
}
After settlement:
newthread () { finalmessagemessage=
Message.restoremessagewithid (Mprovidercontext,messageid); if (message==null) { return;  &NBSP} accountaccount=account.restoreaccountwithid (MProviderContext,
Message.maccountkey); if (account==null) { return;//
Ismessagingcontroller returns false for null, but let ' S make itclear.    &NBSP} if (Ismessagingcontroller (account)) {
mlegacycontroller.processpendingactions (Message.maccountkey);    &NBSP}}.start ();
about asynctask:http://developer.android.com/reference/android/os/asynctask.html
Case 2: Keywords: reading and writing network data on the UI thread
anrin process: com.android.mediascape:photoviewer (Last incom.android.mediascape:
Photoviewer) annotation:keydispatchingtimedout cpu usage: load: 6.74 / 6.89 / 6.12 cpuusage from 8254ms to 3224ms ago: ovider.webmedia: 4% = 4% user +0% kernel / faults: 68 minor system_ Server: 2% = 1% user + 0%kernel / faults: 18 minor re-initialized>: 0% = 0% user + 0%kernel / faults
: 50 minor events/0: 0% = 0% user + 0%kernel total:7% = 6% user + 1% kernel dalvikthreads: "" Main "" prio=5 tid=3 native |group= "" Main "" Scount=1 dscount=0 s=yobj=0x4001b240 self=0xbda8 | systid=2579 nice=0 sched=0/0cgrp=unknown handle=-1343993184 Atorg.apache.harmony.luni.platform.OSNetworkSystem.receiveStreamImpl (Nativemethod) Atorg.apache.harmony.luni.platform.OSNetworkSystem.receiveStream (osnetworksystem.java:478) atorg.apache.harmony.luni.net.plainsocketimpl.read (plainsocketimpl.java:565) Atorg.apache.harmony.luni.net.SocketInputStream.read (socketinputstream.java:87) Atorg.apache.harmony.luni.internal.net.www.protocol.http.httpurlconnection$limitedinputstream.read ( httpurlconnection.java:303) atjava.io.inputstream.read (InputStream.java:133) atjava.io.bufferedinputstream.fillbuf (BUFFEREDINPutstream.java:157) atjava.io.bufferedinputstream.read (BufferedInputStream.java:346) atandroid.graphics.bitmapfactory.nativedecodestream (Native Method) atandroid.graphics.bitmapfactory.decodestream (bitmapfactory.java:459) Atcom.android.mediascape.activity.PhotoViewerActivity.getPreviewImage (photovieweractivity.java:4465) atcom.android.mediascape.activity.photovieweractivity.disppreview (PhotoViewerActivity.java : 4406) atcom.android.mediascape.activity.photovieweractivity.access$6500 ( photovieweractivity.java:125) atcom.android.mediascape.activity.photovieweractivity$33$ 1.run (photovieweractivity.java:4558) atandroid.os.handler.handlecallback (Handler.java : 587) atandroid.os.handler.dispatchmessage (handler.java:92) Atandroid.os.Looper.loop (looper.java:1) atandroid.app.activitythread.main (activitythread.java:4370) Atjava.lang.reflect.Method.invokeNative (Native method) Atjava.lang.reflect.Method.invoke (method.java:521) atcom.android.internal.os.zygoteinit $MethodAndArgsCaller. Run (zygoteinit.java:868) atcom.android.internal.os.zygoteinit.main (zygoteinit.java:626) atdalvik.system.nativestart.main (Native Method)
about network connections, you can set up a timeout time when you design it or put it into a separate thread for processing.
about Handler issues, refer to: http://developer.android.com/reference/android/os/Handler.html
Case 3: Keywords: memoryleak/thread leak
11-1621:41:42.560 i/activitymanager ( 1190): anr in process:android.process.acore (Last in android.process.acore) 11-1621:41:42.560 i/activitymanager ( 1190): Annotation:keydispatchingtimedout 11-16 21:41:42.560 i/activitymanager (1190): cpu usage: 11-16 21:41:42.560 i/activitymanager ( 1190): Load: 11.5 / 11.1 / 11.09 11-16 21:41:42.560 i/ Activitymanager (1190): cpu usage from 9046ms to 4018ms ago: 11-16 21:41:42.560i/activitymanager ( 1190): d.process.acore:98%= 97% user + 0% kernel / faults: 1134 minor 11-16 21:41:42.560i/activitymanager ( 1190): system_server: 0% = 0% user + 0% kernel /faults: 1&nBsp;minor 11-16 21:41:42.560 i/activitymanager ( 1190): adbd:0% = 0% user + 0% kernel 11-16 21:41:42.560 i/ Activitymanager (1190): logcat: 0% = 0% user + 0% kernel 11-16 21:41:42.560i/activitymanager ( 1190): total:100% = 98% user + 1% kernel cmdline: android.process.acore dalvik threads: "main" prio=5 tid=3 vmwait |group= "main" scount=1 dscount=0 s=n obj=0x40026240self=0xbda8 | systid=1815 nice=0 sched=0/0 cgrp=unknownhandle=-1344001376 atdalvik.system.vmruntime.trackexternalallocation (Nativemethod) Atandroid.graphics.Bitmap.nativeCreate (Native method) atandroid.graphics.bitmap.createbitmap (Bitmap.java:468) atandroid.view.view.builddrawingcache (view.java:6324) Atandroid.view.View.getDrawingCache (view.java:6178) atandroid.view.viewgroup.drawchild ( viewgroup.java:1541)   ... Atcom.android.internal.policy.impl.phonewindow$decorview.draw (phonewindow.java:1830) Atandroid.view.ViewRoot.draw (viewroot.java:1349) Atandroid.view.ViewRoot.performTraversals (viewroot.java:1114) Atandroid.view.ViewRoot.handleMessage (viewroot.java:1633) Atandroid.os.Handler.dispatchMessage (handler.java:99) atandroid.os.looper.loop ( looper.java:123) atandroid.app.activitythread.main (activitythread.java:4370) atjava.lang.reflect.method.invokenative (Native method) atjava.lang.reflect.method.invoke (Method.java:521) atcom.android.internal.os.zygoteinit$methodandargscaller.run (zygoteinit.java:868) atcom.android.internal.os.zygoteinit.main (zygoteinit.java:626) Atdalvik.system.NativeStart.main (Native method) "Thread-408" prio=5 tid= 329 wait |group= "main" scount=1 dscount=0 s=n obj= 0x46910d40self=0xcd0548 | systid=10602 nice=0 sched=0/0 cgrp= unknownhandle=15470792 at java.lang.object.wait (Native Method) -waiting on <0x468cd420> (A java.lang.object) Atjava.lang.Object.wait (object.java:288) atcom.android.dialer.calllogcontenthelper$ Uiupdaterexecutor$1.run (Calllogcontenthelper.java:289) atjava.lang.thread.run (thread.java:1096)
Analysis:
Atdalvik.system.VMRuntime.trackExternalAllocation (Nativemethod) low memory causes block to be created on bitmap
**meminfo in PID 1360 [Android.process.acore] * *
Native Dalvik
size:17036 23111 N/a 40147
allocated:16484 20675 N/a 37159
free:296 2436 N/a 2732
WORKAROUND: If the machine's memory family can modify the virtual machine's memory to 36M or greater, but it is best to review the code to see which memory is not released
Some thoughts on the ANR in Android
Previously doing Android system development, generally rarely write programs. Now go to a company to do the Android Internet application, the program occasionally appears some ANR.
Shangfeng to ANR very attention, expect I can completely solve the project ANR. ⊙?⊙ b Khan!
So I have some thinking about ANR, and and just from Tencent QQ project team to the company's headquarters in Beijing, a colleague of the architect to discuss. He also basically agrees with my point of view.
Now I have to deal with the idea of ANR as follows:
First, before the project, should ensure that the engineers understand the rationale for generating ANR, handler the basic principles, understand some of the main callback functions of the execution thread. If the engineers are not meeting these requirements, they should try to get the engineers to know the knowledge through training and other means.
Knowledge of these technologies is available in reference to the official recommendations on ANR and the Android threading model and the Looper and handler.
Second, if the program in the initialization phase more time-consuming, consider displaying a splash screen or as soon as possible to let the main view quickly display processing, and then show other views. In either case, try to show that the program is running forward so that the user does not feel the application is frozen.
Thirdly, architects should use the MVC architecture as far as possible in architecture design, and be aware that the code should be executed in the main thread, and that the code should be executed in a non main thread. Of course, it is not easy to do the framework! ⊙?⊙ b Khan!
Iv. for the late stage of the project, instead of adopting the MVC framework, or using the MVC framework but not very well implemented projects, should draw its overall frame diagram, time series diagram analysis, as far as possible to use a small price, step-by-step iterative way to let its project finally achieve a good MVC architecture. For our current project, I'm trying to use this approach to minimize ANR. I do not know whether the final can achieve very good results.
When coding, the engineer must consider whether the current code is dead in the main thread, or if the current code is a time-consuming operation;
Whether the thread is competing with the lock can cause code to wait, and it takes too much time, and if the code can cause a deadlock, it generates ANR.
If third party applications are used in the application, please take these third-party applications as separate processes to avoid its undesirable code and cause the project to appear ANR. For this technology please refer to the Android single APK application multi-process
Seven, in the process of running, there are ANR, engineers should be/data/anr/traces.txt and combined with the code, ANR analysis.
In the late part of the project, you can use Strictmode to help you find potentially time-consuming operations in the main thread, such as network or database operations.
Nine, in the late project, should be through monkey and so on to carry out the pressure test, to identify potential ANR, and to modify.
For the use of Monkey, refer to the monkey usage of Android.
For some important ANR and bad code, should be summarized and summarized, form a document, in order to share with other colleagues or project team, and as a new employee training materials.
Summarize
Whenever a ANR is produced we can solve it according to the/data/anr/traces.txt analysis, but it is difficult to fundamentally solve the problem, only by introducing a good framework (such as the MVC Framework), upgrading the development Engineer's cognition and technology accumulation to avoid it.