開發階段需要一個輕量、可控的除錯工具類,支援:
Log.i、System.out)public final class AndroidDebug {
private static boolean sDebugEnabled = false;
private static Thread sMonitorThread;
private static long sLastFreeMemory = 0;
/** 全域開關,建議在 Application.onCreate() 依 BuildConfig.DEBUG 設定 */
public static void setDebugEnabled(boolean enabled) {
sDebugEnabled = enabled;
}
public static boolean isDebugEnabled() {
return sDebugEnabled;
}
/** 簡易輸出 */
public static void log(String tag, String msg) {
if (sDebugEnabled) Log.i(tag, msg);
}
public static void println(String msg) {
if (sDebugEnabled) System.out.println(msg);
}
/** 強制 GC(僅供除錯觀察) */
public static void gc() {
if (sDebugEnabled) System.gc();
}
/** 列印堆記憶體總量 */
public static void printTotalMemory() {
if (!sDebugEnabled) return;
Runtime rt = Runtime.getRuntime();
println("Total memory: " + formatBytes(rt.totalMemory()));
}
/** 列印剩餘記憶體 */
public static void printFreeMemory() {
if (!sDebugEnabled) return;
gc();
Runtime rt = Runtime.getRuntime();
println("Free memory: " + formatBytes(rt.freeMemory()));
}
/** 列印記憶體變化量(正數=釋放,負數=佔用) */
public static void printMemoryDelta() {
if (!sDebugEnabled) return;
gc();
Runtime rt = Runtime.getRuntime();
long freeNow = rt.freeMemory();
long delta = freeNow - sLastFreeMemory;
sLastFreeMemory = freeNow;
if (delta > 0) println("Memory freed: " + formatBytes(delta));
else if (delta < 0) println("Memory allocated: " + formatBytes(-delta));
}
/** 啟動/停止背景記憶體監控(每 100ms 採樣一次) */
public static void setMemoryMonitoring(boolean enable) {
if (enable) {
if (sMonitorThread == null) {
sMonitorThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(100);
printMemoryDelta();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}, "MemoryMonitor");
sMonitorThread.setDaemon(true);
sMonitorThread.start();
}
} else {
if (sMonitorThread != null) {
sMonitorThread.interrupt();
sMonitorThread = null;
}
}
}
private static String formatBytes(long bytes) {
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return String.format("%.2f KB", bytes / 1024f);
return String.format("%.2f MB", bytes / (1024f * 1024f));
}
}
// Application 初始化
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
AndroidDebug.setDebugEnabled(BuildConfig.DEBUG);
// 開發期可開啟背景監控
if (BuildConfig.DEBUG) AndroidDebug.setMemoryMonitoring(true);
}
}
// 任意處呼叫
AndroidDebug.log("Network", "Request: " + url);
AndroidDebug.printFreeMemory();
BuildConfig.DEBUG,Release 版本編譯時自動移除所有除錯代碼(需啟用 R8/ProGuard)。