zoukankan      html  css  js  c++  java
  • 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显示的是单个方法一次调用执行时间。
  • 相关阅读:
    关于maven的一些记录
    3des和tomcat部署
    java串口通讯
    mina自定义编解码
    Linux 下关闭防火墙设置
    查看本机IP
    linux修改localhost方法
    centos 6.5下使用中文输入法
    linux:can't save files
    ng-model取不到值的问题
  • 原文地址:https://www.cnblogs.com/yongfengnice/p/6928314.html
Copyright © 2011-2022 走看看