实现文件:
PrintStackTrace.java
"
package com.android.providers.downloads;
import android.util.Log;
public class PrintStackTrace {
//Invoke the static method where you want to print a stack trace
public static void printStackTrace(Class cls) {
StackTraceElement[] elements = (new Throwable()).getStackTrace();
StringBuffer buf = new StringBuffer();
buf.append("Stack for " cls.getName() ":");
for(int i=0; i<elements.length; i ) {
buf.append("\n "
elements[i].getClassName()
"."
elements[i].getMethodName()
"("
elements[i].getFileName()
":"
elements[i].getLineNumber()
")");
}
//System.out.println(buf.toString());
Log.i("ahking", " " buf.toString());
}
/*
public static void main(String args[]) {
//An example to show how to invoke it
printStackTrace(Test.class);
}
*/
}
"
调用的地方:
PrintStackTrace.printStackTrace(DownloadThread.class); //把当前类.class传进去.
Log输出:
01-01 00:03:55.648 I/ahking ( 1513): Stack for com.android.providers.downloads.DownloadThread:
01-01 00:03:55.648 I/ahking ( 1513): com.android.providers.downloads.PrintStackTrace.printStackTrace(PrintStackTrace.java:10)
01-01 00:03:55.648 I/ahking ( 1513): com.android.providers.downloads.DownloadThread.transferData(DownloadThread.java:285)
01-01 00:03:55.648 I/ahking ( 1513): com.android.providers.downloads.DownloadThread.executeDownload(DownloadThread.java:254)
01-01 00:03:55.648 I/ahking ( 1513): com.android.providers.downloads.DownloadThread.run(DownloadThread.java:182)
看工程时, 分析不出来当前函数是如何被调用到的, 用这个方法非常有用.
更简单的方式:
(new Throwable()).printStackTrace();
Log输出, 在log中搜System.err关键字就可以了:
01-01 00:33:36.398 W/System.err( 1525): java.lang.Throwable
01-01 00:33:36.398 W/System.err( 1525): at com.android.providers.downloads.DownloadThread.transferData(DownloadThread.java:287)
01-01 00:33:36.398 W/System.err( 1525): at com.android.providers.downloads.DownloadThread.executeDownload(DownloadThread.java:254)
01-01 00:33:36.406 W/System.err( 1525): at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:182)