Android调试程序技巧
- - ITeye博客在开发的过程中我们经常需要调试程序的执行路径,如我们想知道一个Activity的生命周期方法的调用顺序,我们可能会写如下代码. 这样每次都要输入两个参数,有没有更简便的方法呢. 我们可以通过Thread.currentThread().getStackTrace()获取当前堆栈调用信息,从堆栈信息中可以获取当前调用的java文件名,类名,方法名和代码行号.
..... public void onResume() { super.onResume(); Log.d("Tag","onResume()"); } public void onStart() { super.onStart(); Log.d("Tag","onStart()"); } public void onPause() { super.onPause(); Log.d("Tag","onPause()"); } public void onStop() { super.onStop(); Log.d("Tag","onStop()"); } ...
package cn.caiwb; import android.util.Log; public final class LogHelper { private static boolean mIsDebugMode = true;//获取堆栈信息会影响性能,发布应用时记得关闭DebugMode private static String mLogTag = "LogHelper"; private static final String CLASS_METHOD_LINE_FORMAT = "%s.%s() Line:%d (%s)"; public static void trace() { if (mIsDebugMode) { StackTraceElement traceElement = Thread.currentThread() .getStackTrace()[3];//从堆栈信息中获取当前被调用的方法信息 String logText = String.format(CLASS_METHOD_LINE_FORMAT, traceElement.getClassName(), traceElement.getMethodName(), traceElement.getLineNumber(), traceElement.getFileName()); Log.d(mLogTag, logText);//打印Log } } }
package cn.caiwb; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class LogHelperActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LogHelper.trace(); } @Override public void onStart() { super.onStart(); LogHelper.trace(); } @Override public void onResume() { super.onResume(); LogHelper.trace(); } @Override public void onPause() { super.onPause(); LogHelper.trace(); } @Override public void onStop() { super.onStop(); LogHelper.trace(); } @Override public void onDestroy() { super.onDestroy(); LogHelper.trace(); } }