Android出现ANR的分析,以及TraceView的使用

  1. 主线程耗时操作超过5秒,会出现ANR无响应
    可使用TraveView查看哪个方法调用导致的,查看步骤看截图说明:

    附:有可能看见很多操作是超过5秒的,可是别忘记了是在主线程耗时超过5秒才会导致ANR,子线程是不会,所以耗时操作需要在子线程完成。
    附:跟踪的时间尽量短一些,问题重现即可,只有分析起来容易很多。

2.常见的导致ANR出现的因素:

1)主线程IO操作

2)死锁

3)广播广播监听器里执行耗时操作
    如果确实需要在广播里执行耗时操作,可这样处理:
    3-1) 方法一,使用IntentService:
        @Override
        public void onReceive(Context context, Intent intent) {
            // The task now runs on a worker thread.
            Intent intentService = new Intent(context, MyIntentService.class);
            context.startService(intentService);
        }
        public class MyIntentService extends IntentService {
               @Override
               protected void onHandleIntent(@Nullable Intent intent) {
               BubbleSort.sort(data);
           }
        }
    3-2)方法二,使用 goAsync():
        @Override
        public void onReceive(Context context, Intent intent) {
            final PendingResult pendingResult = goAsync();
            new AsyncTask<Integer[], Integer, Long>() {
               @Override
               protected Long doInBackground(Integer[]... params) {
                   // This is a long-running operation
                   BubbleSort.sort(params[0]);
                   pendingResult.finish();
               }
            }.execute(data);
        }

4)递归调用
        这种情况,也许单个方法的调用执行时间很短,但是递归调用同样会造成ANR出现;而且这样情况很难通过TraceView观看出来,因为TraceView显示的是单个方法一次调用执行时间。
posted @ 2017-06-01 12:40  yongfengnice  阅读(2146)  评论(0编辑  收藏  举报