轉載自:http://blog.csdn.net/mylzc/article/details/6827230html
介紹:在開發的過程當中咱們常常須要調試程序的執行路徑,如咱們想知道一個Activity的生命週期方法的調用順序,咱們可能會寫以下代碼: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()");
- }
-
- ...
這樣每次都要輸入兩個參數,有沒有更簡便的方法呢?android
咱們能夠經過Thread.currentThread().getStackTrace()獲取當前堆棧調用信息,從堆棧信息中能夠獲取當前調用的java文件名,類名,方法名和代碼行號。app
因而,咱們封裝了一個工具類LogHelper。咱們只須要使用這個工具類,在跟蹤的位置調用LogHelper.trace()方法就能夠打印當前調用方法的信息。ide
例子:打印Activity的生命週期方法執行流程。工具
LogHelper.java性能
- package com.zhuozhuo;
-
- import android.util.Log;
-
- public final class LogHelper {
- private static boolean mIsDebugMode = true;
- 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);
- }
- }
- }
LogHelperActivity.javaspa
- package com.zhuozhuo;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
-
- public class LogHelperActivity extends Activity {
-
-
-
- @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();
- }
- }
Log打印結果:.net
總結:調試
經過使用LogHelper的trace()方法,在調試的時候咱們能夠很是方便地打印應用的執行流程。