Android 开发:打印主线程方法栈

除了严格模式外,还可以通过打印主线程方法栈的方式找到耗时操作:

new Thread(){
    public void run(){
        while (true)
        {
            try {
                Map map=Thread.getAllStackTraces();
               Set> stackTraceElementEntry=map.entrySet();
                for(Map.Entry entry:stackTraceElementEntry)
                {
                    Thread t=entry.getKey();
                    StackTraceElement[] stackTraceElements=t.getStackTrace();
                    if(t.getName().equals("main"))
                    {
                        String Tag="STACK_TRACE";
                        for(StackTraceElement stackTraceElement:stackTraceElements)
                        {
                            Log.d(Tag,stackTraceElement.getLineNumber()+" "+stackTraceElement.getClassName()+stackTraceElement.getMethodName());
                        }
                    }
                }
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}.start();