"Android" [goto] analysis and problem handling of ANR

Source: Internet
Author: User
Tags cpu usage

One: What is ANR

Anr:application not responding, i.e. application unresponsive

II: Type of ANR

There are generally three types of ANR:

1. Keydispatchtimeout (5 seconds)--key type keys or touch events are not responding at a specific time

2. Broadcasttimeout (seconds)--broadcastreceiver cannot process the completion at a specific time

3. Servicetimeout (seconds)-small probability type service cannot process completion at a specific time

Three: Keydispatchtimeout

Akey or touch event is not dispatched within the specified time (key or touch events are not responding for a specific period)

The specific time-out is defined under the framework of the Activitymanagerservice.java

How long we wait for until we timeout on key dispatching.

staticfinal int key_dispatching_timeout = 5*1000

Four: Why does it time out?

The time-out count is usually started by distributing the button to the app. There are two common reasons for timeouts:

(1) The current event does not have a chance to be processed (i.e. UI line is impersonating in the previous event, not completed in a timely manner or looper blocked for some reason)

(2) The current event is 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, network connections, or other actions that might hinder the UI thread) putting it into a separate thread processing

3. Try to use handler to handle interactions between Uithread and other thread

VI: UI thread

Speaking of so many UI threads, which ones are part of the UI thread?

The UI thread mainly includes 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 the ANR

Look at a log first:

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 T Imedout sending tocom.android.email/com.android.email.activity.splitscreenactivity 04-01 13:12:14.123 I/Process (22 0): Sending signal.     pid:21404 Sig:3---The time of the ANR and the time to generate the 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 (): 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 6 99ms ago----CPU usage before ANR occurs 04-0113:12:15.872 E/activitymanager: 5.5%21404/COM.Android.email:1.3% user + 4.1% kernel/faults:10 minor 04-0113:12:15.872 E/activitymanager (UP): 4.3%220/system_s erver:2.7% user + 1.5% kernel/faults:11 minor 2 major 04-0113:12:15.872 E/activitymanager (UP): 0.9%52/SPI_QSD. 0:0% user + 0.9% kernel 04-0113:12:15.872 e/activitymanager (UP): 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/Activi Tymanager: 100%total:4.8% user + 7.6% kernel + 87% iowait 04-0113:12:15.872 E/activitymanager (UP): CPUUsage fr Om 3697ms to 4223ms later:--ANR CPU Usage 04-0113:12:15.872 e/activitymanager: 25%21404/com.android.email:25% use R + 0% kernel/faults:191 minor 04-0113:12:15.872 E/activitymanager (UP): 16% 21603/__eas (par.hakan:16% user + 0% K Ernel 04-0113:12:15.872 E/activitymanager (): 7.2% 21406/gc:7.2% user + 0% kernel 04-0113:12:15.872 E/ActivityMa Nager (220): 1.8% 21409/compiler:1.8% user + 0% kernel 04-0113:12:15.872 e/activitymanager (UP): 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-011     3:12:15.872 E/activitymanager: 32%total:28% user + 3.7% kernel

From 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 starvation caused by the ANR

If the CPU usage is small, the main thread is block

If the iowait is high, it is possible that the ANR is the main thread that caused the I/O operation

In addition to looking at log, to resolve the ANR also need to Trace.txt file,

How to get it? You can use the following command to get

$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, the most visible information is the following:

  -----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)    


Indicates that the main thread is waiting for the next message to enter the message queue

Eight: Thread status

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,/* off 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 resolve the ANR

1. First Analyze log

2. View the call stack from the Trace.txt file.

3. See the Code

4. Take a closer look at the cause of the ANR (Iowait?block?memoryleak?)

Ten: Case Study 1: Keywords: contentresolver in asynctask onpostexecute, high iowait
Process:com.android.email activity:com.android.email/.activity.  Messageview subject:keydispatchingtimedout CPU usage from 2550ms to-2814ms ago:5%187/system_server:3.5% user +     1.4% kernel/faults:86 minor 20major 4.4% 1134/com.android.email:0.7% user + 3.7% kernel/faults:38 minor 4% 372/com.android.eventstream:0.7%user + 3.3% kernel/faults:6 minor 1.1% 272/com.android.phone:0.9% user + 0.1 % kernel/faults:33 Minor 0.9%252/com.android.systemui:0.9% user + 0% kernel 0%409/com.android.eventstream.teleph onyplugin:0% user + 0% Kernel/faults:2 minor 0.1% 632/com.android.devicemonitor:0.1% user + 0%kernel 100%TOTAL: 6.9% user + 8.2% kernel +84%iowait-----pid 1134 at 2010-12-17 17:46:51-----Cmd line:com.android.email DALVIK T  Hreads: (mutexes:tll=0 tsl=0tscl=0 ghl=0 hwl=0 hwll=0) "main" prio=5 tid=1 WAIT |group= "main" Scount=1 dscount=0 Obj=0x2aaca180self=0xcf20 | systid=1134 nice=0 sched=0/0 Cgrp=[fopen-error:2]handle=1876218976 at java.lang.Object.wait (Native Method)-waiting on <0x2aaca218> (a java.lang.VMThread)    Atjava.lang.Thread.parkFor (thread.java:1424) atjava.lang.LangAccessImpl.parkFor (langaccessimpl.java:48)    Atsun.misc.Unsafe.park (unsafe.java:337) Atjava.util.concurrent.locks.LockSupport.park (locksupport.java:157) Atjava.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt (Abstractqueuedsynchronizer.java : 808) atjava.util.concurrent.locks.AbstractQueuedSynchronizer.acquireQueued (abstractqueuedsynchronizer.java:841    ) Atjava.util.concurrent.locks.AbstractQueuedSynchronizer.acquire (abstractqueuedsynchronizer.java:1171)    Atjava.util.concurrent.locks.reentrantlock$fairsync.lock (reentrantlock.java:200)    Atjava.util.concurrent.locks.ReentrantLock.lock (reentrantlock.java:261) Atandroid.database.sqlite.SQLiteDatabase.lock (sqlitedatabase.java:378) atandroid.database.sqlite.SQLiteCursor. <init> (sqlitecursor.java:222) atandroid.Database.sqlite.SQLiteDirectCursorDriver.query (sqlitedirectcursordriver.java:53)    Atandroid.database.sqlite.SQLiteDatabase.rawQueryWithFactory (sqlitedatabase.java:1356)    Atandroid.database.sqlite.SQLiteDatabase.queryWithFactory (sqlitedatabase.java:1235)    Atandroid.database.sqlite.SQLiteDatabase.query (sqlitedatabase.java:1189)    Atandroid.database.sqlite.SQLiteDatabase.query (sqlitedatabase.java:1271) Atcom.android.email.provider.EmailProvider.query (emailprovider.java:1098) atandroid.content.contentprovider$    Transport.query (contentprovider.java:187) atandroid.content.ContentResolver.query (contentresolver.java:268)    Atcom.android.email.provider.emailcontent$message.restoremessagewithid (emailcontent.java:648)    Atcom.android.email.Controller.setMessageRead (controller.java:658)    Atcom.android.email.activity.MessageView.onMarkAsRead (messageview.java:700)    atcom.android.email.activity.messageview.access$2500 (messageview.java:98) Atcom.android.email.activity.MessageVieW$loadbodytask.onpostexecute (messageview.java:1290) atcom.android.email.activity.messageview$    Loadbodytask.onpostexecute (messageview.java:1255) atandroid.os.AsyncTask.finish (asynctask.java:417) atandroid.os.asynctask.access$300 (asynctask.java:127) atandroid.os.asynctask$internalhandler.handlemessage ( asynctask.java:429) atandroid.os.Handler.dispatchMessage (handler.java:99) Atandroid.os.Looper.loop (Looper.java : 123) Atandroid.app.ActivityThread.main (activitythread.java:3652) atjava.lang.reflect.Method.invokeNative (Native     Method) Atjava.lang.reflect.Method.invoke (method.java:507) atcom.android.internal.os.ZygoteIn

Cause: The iowait is high, indicating that the current system is busy with I/O, so database operations are 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, and let's make itclear.} if (Ismessagingcontroller (account)) {new Thread () {@Overridepublic void run () { Mlegacycontroller.processpendingactions (Message.maccountkey);}}. Start ();}

After resolution:

Newthread () {Finalmessagemessage=message.restoremessagewithid (Mprovidercontext,messageid); if (message==null) { return;} Accountaccount=account.restoreaccountwithid (Mprovidercontext,message.maccountkey); if (account==null) {return;// Ismessagingcontroller returns false for null, and let's make itclear.} if (Ismessagingcontroller (account)) {mlegacycontroller.processpendingactions (Message.maccountkey);}}. Start ();

About asynctask:http://developer.android.com/reference/android/os/asynctask.html

Case 2: Keywords: Read and write 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-initialize    D&gt: 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: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)

With respect to the network connection, you can set a timeout time or put it on a separate thread when designing.

For Handler questions, 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-162 1: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/ActivityManage  R (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 minor 11-16 21:41:42.560 I/activitymanager (1190): adbd:0% = 0% user + 0% kernel 11-16 21:41:42.560 i/acti  Vitymanager (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 DsC Ount=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.Pho    Newindow$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 <0x    468cd420> (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) Insufficient memory causes block to be created on bitmap

**meminfo in PID 1360 [Android.process.acore] * *

Native Dalvik Other Total

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, it is best to review the code to see which memory is not released

Transferred from: http://www.cnblogs.com/purediy/p/3225060.html

"Android" [goto] analysis and problem handling of ANR

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.