ANR异常及traces信息解析

ANR(Application Not Responding)定义

在Android上,如果你的应用程序有一段时间响应不够灵敏,系统会向用户显示一个对话框,这个对话框称作应用程序无响应(ANR:Application Not Responding)对话框。用户可以选择“等待”而让程序继续运行,也可以选择“强制关闭”。所以一个流畅的合理的应用程序中不能出现anr,而让用户每次都要处理这个对话框。因此,在程序里对响应性能的设计很重要,这样系统不会显示ANR给用户。
 

出现ANR的原因

默认情况下,在android中Activity的最长执行时间是5秒,BroadcastReceiver的最长执行时间则是10秒。超出就会提示应用程序无响应(ANR:Application Not Responding)对话框。
 

三种常见类型

1:KeyDispatchTimeout(5 seconds) --主要类型

按键或触摸事件在特定时间内无响应

2BroadcastTimeout(10 seconds)

BroadcastReceiver在特定时间内无法处理完成

3:ServiceTimeout(20 seconds) --小概率类型

Service在特定的时间内无法处理完成

如何分析ANR生成的Traces

出现Application Not Responding的提示后,系统会将日志LOG写到到 data\anr\traces.txt文件
 
举一个简单的例子,下面给出一段日志LOG供参考
 
复制代码
DALVIK THREADS:
(mutexes: tll=0 tsl=0 tscl=0 ghl=0 hwl=0 hwll=0)
"main" prio=5 tid=1 NATIVE
  | group="main" sCount=1 dsCount=0 obj=0x40025340 self=0xd180
  | sysTid=1071 nice=0 sched=0/0 cgrp=default handle=-1344994080
  | schedstat=( 2355584448 1199910712 3410 )
  at java.net.InetAddress.getaddrinfo(Native Method)
  at java.net.InetAddress.lookupHostByName(InetAddress.java:540)
  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:333)
  at java.net.InetAddress.getAllByName(InetAddress.java:295)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:100)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:79)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:353)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:120)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:316)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:298)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:236)
  at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:645)
  at com.rayray.cool.util.URLUtil.invokeURL(URLUtil.java:136)
  at com.rayray.cool.activity.WoDeJianYiActivity$1.onClick(WoDeJianYiActivity.java:173)
  at android.view.View.performClick(View.java:2535)
  at android.view.View$PerformClick.run(View.java:9129)
  at android.os.Handler.handleCallback(Handler.java:618)
  at android.os.Handler.dispatchMessage(Handler.java:123)
  at android.os.Looper.loop(SourceFile:351)
  at android.app.ActivityThread.main(ActivityThread.java:3821)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:538)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:969)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:727)
  at dalvik.system.NativeStart.main(Native Method)
复制代码

出现ANR问题的原因就是上面红色代码中

at com.rayray.cool.activity.WoDeJianYiActivity$1.onClick(WoDeJianYiActivity.java:173) 是Android中Activity
at com.rayray.cool.util.URLUtil.invokeURL(URLUtil.java:136) 是一次耗时的联网请求


Activity中的按键事件在特定事件内未响应造成。


如何解决ANR

(1)耗时的操作放入单独的线程中处理,如(联网、数据库、IO)

(2)尽量避免和UI线程的操作

 

原创声明

本文出自 Ray-Ray的博客

文章地址 http://www.cnblogs.com/rayray/archive/2013/03/09/2932043.html

避免Android开发中的ANR


ANR是什么

ANRs (“Application Not Responding”),意思是”应用没有响应“。

在如下情况下,Android会报出ANR错误:

– 主线程 (“事件处理线程” / “UI线程”) 在5秒内没有响应输入事件

– BroadcastReceiver 没有在10秒内完成返回

通常情况下,下面这些做法会导致ANR

1、在主线程内进行网络操作

2、在主线程内进行一些缓慢的磁盘操作(例如执行没有优化过的SQL查询)

应用应该在5秒或者10秒内响应,否则用户会觉得“这个应用很垃圾”“烂”“慢”...等等

一些数据(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的数据

android.os.AsyncTask

AsyncTask 可以与UI线程很方便的配合,这个类可以在后台执行一些操作,并在执行结束的时候将结果发布到UI线程中去,并且无需使用线程或handler来控制。

例子:

private class DownloadFilesTask extends AsyncTask {
    protected Long doInBackground(URL... urls) {  // on some background thread
            int count = urls.length;
            long totalSize = 0;
            for (int i = 0; i < count; i++) {
                totalSize += Downloader.downloadFile(urls[i]);
                publishProgress((int) ((i / (float) count) * 100));
            }

            return totalSize;
        } 

        protected void onProgressUpdate(Integer... progress) {  // on UI thread!
        setProgressPercent(progress[0]);
    } 

    protected void onPostExecute(Long result) {  // on UI thread!
        showDialog("Downloaded " + result + " bytes");
    }
} 

new DownloadFilesTask().execute(url1, url2, url3);  // call from UI thread!
private boolean handleWebSearchRequest(final ContentResolver cr) {
            ...
    new AsyncTask() {
        protected Void doInBackground(Void... unused) {
            Browser.updateVisitedHistory(cr, newUrl, false);
            Browser.addSearchUrl(cr, newUrl);
            return null;
        } 

    }.execute()
            ...
    return true; 

}

AsyncTask要点

1、必须从主线程调用,或者线程中有Handler或Looper。

2、不要在一个可能会被另外一个AsyncTask调用的库里面使用AsyncTask(AsyncTask是不可重入的)

3、如果从一个activity中调用,activity进程可能会在AsyncTask结束前退出,例如:

  • 用户退出了activity
  • 系统内存不足
  • 系统暂存了activity的状态留待后用
  • 系统干掉了你的线程

如果AsyncTask中的工作很重要,应该使用......

android.app.IntentService

Eclair(2.0, 2.1)文档中说:

“An abstract Service that serializes the handling of the Intents passed upon service start and handles them on a handler  thread.  To use this class extend it and implement onHandleIntent(Intent). The Service will automatically be  stopped when the last enqueued Intent is handled.” 有点令人困惑,因此...几乎没人用

Froyo (2.2) 的文档, 又澄清了一下....

android.app.IntentService

“IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests  through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself  when it runs out of work.

This 'work queue processor' pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to  simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService  will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but  only one request will be processed at a time.”

IntentService 的好处

  • Acitivity的进程,当处理Intent的时候,会产生一个对应的Service
  • Android的进程处理器现在会尽可能的不kill掉你
  • 非常容易使用

日历中IntentService的应用

public class DismissAllAlarmsService extends IntentService {
    @Override public void onHandleIntent(Intent unusedIntent) {
        ContentResolver resolver = getContentResolver();
        ...
        resolver.update(uri, values, selection, null);
    }
}
in AlertReceiver extends BroadcastReceiver, onReceive():  (main thread)
    Intent intent = new Intent(context, DismissAllAlarmsService.class);
    context.startService(intent);

其它技巧

1、当启动AsyncTask的时候,立刻disable UI元素(按钮等等)。

2、显示一些动画,表示在处理中

3、使用进度条对话框

4、使用一个定时器作为耗时警告,在AsyncTask开始时启动定时器,在AsyncTask的onPostExecute方法中取消定时器。

5、当不确定要耗时多久的时候,组合使用上述所有方法

总结

  • 离开主线程!
  • 磁盘和网络操作不是马上就能完的
  • 了解sqlite在干嘛
  • 进度展示很好

PS,在视频讲座中,作者还提到,Chrome团队为了避免Jank(响应超时而死掉),几乎所有的功能和任务都会在子线程里面去做。这一点也值得在Android中借鉴。

刘金雨译:  避免Android开发中的ANR 全文via:  Writing Zippy Android Apps


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值