以前在C/C++ 開發中,我們可以宏定義,Debug模式下,輸出日誌,方便測試。Release模式下,無日誌輸出。
使用Java時,Java 是解釋語言,無法編譯。就無模式之分了。有沒有辦法實現,Debug、Release版?
debug 輸出日誌、調試信息。
release 發佈版本,無輸出日誌、調試信息。
辦法是人想出來的。
下面說說我的解決方案:
1 模擬C宏定義。
package cn.eben.hpc.define;
public final class BuildConfig {
public final static boolean isDebug = true;// 通過改變isDebug,實現Debug、Release版
}
2 重定義日誌輸出類
package cn.eben.hpc.define;
import java.lang.reflect.Method;
import android.util.Log;
public class Trace {
public final static void e(String tag, String msg, Throwable tr) {
if (BuildConfig.isDebug)
Log.e(tag, msg, tr);
}
public final static void e(String tag, String msg) {
if (BuildConfig.isDebug)
Log.e(tag, msg);
}
public final static void e(String msg) {
if (BuildConfig.isDebug)
Log.e("", msg);
}
public final static void e(Throwable tr) {
if (BuildConfig.isDebug)
Log.e("", "", tr);
}
public final static void d(String tag, String msg) {
if (BuildConfig.isDebug)
Log.d(tag, msg);
}
public final static void d(String msg) {
if (BuildConfig.isDebug)
Log.d("", msg);
}
public final static void d(Throwable tr) {
if (BuildConfig.isDebug)
Log.d("", "", tr);
}
}
3 我們工程中使用:
原來使用
Log.i, Log.d, log.e ...
Log.i(TAG,“log”);
使用重定義的日誌
Trace.i, Trace.d Trace.e...
Trace.i(“”, “”);
發佈版本時,我們只需要將isDebug = false.即可。Release版就乾乾淨淨。無日誌信息。
安畢。
是不是很簡單呀! :)