7

ANR(网络资料整理)

 3 years ago
source link: https://blog.bihe0832.com/anr.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

之前一直想总结整理一下关于ANR的内容,虽然内容不多,但是开发中还是要注意,但是一直偷懒了。正好下午又遇到个ANR,加上今天不想码字,解决完就顺便整理一下吧。

什么是ANR

ANR:Application Not Responding,即应用无响应

ANR的类型

ANR一般有三种类型:

  1. KeyDispatchTimeout(5 seconds) –主要类型,按键或触摸事件在特定时间内无响应

    KeyDispatchTimeout:A key or touch event was not dispatched within the specified time(按键或触摸事件在特定时间内无响应)。具体的超时时间的定义在framework下的ActivityManagerService.java

     //How long we wait until we timeout on key dispatching.
     staticfinal int KEY_DISPATCHING_TIMEOUT = 5*1000
  • BroadcastTimeout(10 seconds) –主要类型,BroadcastReceiver在特定时间内无法处理完成

  • ServiceTimeout(20 seconds) –小概率类型,Service在特定的时间内无法处理完成

如何避免KeyDispatchTimeout

  1. UI线程尽量只做跟UI相关的工作
  • 耗时的工作(比如数据库操作,I/O,连接网络或者别的有可能阻碍UI线程的操作)把它放入单独的线程处理

  • 尽量用Handler来处理UIthread和别的thread之间的交互

UI线程主要包括如下:

  • Activity onCreate(), onResume(), onDestroy(), onKeyDown(), onClick(),etc

  • AsyncTask: onPreExecute(), onProgressUpdate(), onPostExecute(), onCancel,etc

  • Mainthread handler: handleMessage(), post*(runnable r), etc

  • other

为什么会超时

超时时间的计数一般是从按键分发给app开始。超时的原因一般有两种:

  • 当前的事件没有机会得到处理(即UI线程正在处理前一个事件,没有及时的完成或者looper被某种原因阻塞住了)

  • 当前的事件正在处理,但没有及时完成

一些数据(Nexus One为例)

  • ~0.04 ms – 通过管道进程从A->B再从B->A写一个字节;或者(从dalvik)读一个简单的/proc文件

  • ~0.12 ms – 由A->B 再由B->A 进行一次Binder的RPC调用

  • ~5-25 ms – 从未缓冲的flash • ~5-200+(!) ms – 向为缓冲的flash中写点东西(下面是具体数据)

  • 16 ms – 60fps的视频中的一帧

  • 41 ms – 24fps的视频中的一帧

  • 100-200 ms – human perception of slow action

  • 108/350/500/800 ms – 3G网络上ping(可变)

  • ~1-6+ seconds – 通过HTTP在3G网络上获取6k的数据

如何去分析并解决ANR

  1. 首先分析log,初步确认ANR的原因

  2. 从/data/anr/traces.txt文件查看调用stack.

  3. 看代码,结合调用栈定位ANR的成因(iowait?block?memoryleak?)

参考文档:

  • http://www.cnblogs.com/purediy/p/3225060.html

  • http://www.360doc.com/content/12/0226/15/7635_189765894.shtml

  • http://log4think.com/avoid_anr_in_android

  • http://blog.csdn.net/andy_android/article/details/6851828

  • http://blog.csdn.net/wwang196988/article/details/6786764

  • http://android-developers.blogspot.com/2009/05/painless-threading.html




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK