編輯:關於 Android 程式設計
與其到處散落的 Log.d,不如封裝一個統一的工具類,用開關控制是否輸出、是否落檔,上線時把開關一關就乾淨了。這個版本還會自動以日期作為檔名、為每條日誌標上時間戳。
package com.example.callstatus;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.os.Environment;
import android.util.Log;
/**
* Android 開發除錯日誌工具類 [支援保存到 SD 卡]
*
* 需要的權限:
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
* <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
*/
@SuppressLint("SimpleDateFormat")
public class MyLog {
public static final String CACHE_DIR_NAME = "dPhoneLog";
public static boolean isDebugModel = true; // 是否輸出日誌
public static boolean isSaveDebugInfo = true; // 是否保存除錯日誌
public static boolean isSaveCrashInfo = true; // 是否保存報錯日誌
public static void v(final String tag, final String msg) {
if (isDebugModel) {
Log.v(tag, "--> " + msg);
}
}
public static void d(final String tag, final String msg) {
if (isDebugModel) {
Log.d(tag, "--> " + msg);
}
}
public static void i(final String tag, final String msg) {
if (isDebugModel) {
Log.i(tag, "--> " + msg);
}
}
public static void w(final String tag, final String msg) {
if (isDebugModel) {
Log.w(tag, "--> " + msg);
}
}
/** 除錯日誌,便於開發追蹤 */
public static void e(final String tag, final String msg) {
if (isDebugModel) {
Log.e(tag, "--> " + msg);
}
if (isSaveDebugInfo) {
new Thread() {
public void run() {
write(time() + tag + " --> " + msg + "\n");
}
}.start();
}
}
/** try catch 時使用,上線產品可上傳回饋 */
public static void e(final String tag, final Throwable tr) {
if (isSaveCrashInfo) {
new Thread() {
public void run() {
write(time() + tag + " [CRASH] --> " + getStackTraceString(tr) + "\n");
}
}.start();
}
}
/** 取得捕捉到的異常字串 */
public static String getStackTraceString(Throwable tr) {
if (tr == null) {
return "";
}
Throwable t = tr;
while (t != null) {
if (t instanceof UnknownHostException) {
return "";
}
t = t.getCause();
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
tr.printStackTrace(pw);
return sw.toString();
}
/** 標識每條日誌產生的時間 */
private static String time() {
return "[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(System.currentTimeMillis())) + "] ";
}
/** 以年月日作為日誌檔名稱 */
private static String date() {
return new SimpleDateFormat("yyyy-MM-dd")
.format(new Date(System.currentTimeMillis()));
}
/** 保存到日誌檔 */
public static synchronized void write(String content) {
try {
FileWriter writer = new FileWriter(getFile(), true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/** 取得日誌檔路徑 */
public static String getFile() {
File sdDir = null;
if (Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED)) {
sdDir = Environment.getExternalStorageDirectory();
}
File cacheDir = new File(sdDir + File.separator + CACHE_DIR_NAME);
if (!cacheDir.exists()) {
cacheDir.mkdir();
}
File filePath = new File(cacheDir + File.separator + date() + ".txt");
return filePath.toString();
}
}
三個開關:isDebugModel 控制 logcat 輸出、isSaveDebugInfo 控制除錯日誌落檔、isSaveCrashInfo 控制異常堆疊落檔。上線時把前兩個關掉即可,不必回頭改程式碼。
為什麼用子線程寫檔:檔案 I/O 是阻塞操作,在主線程寫會拖慢 UI,因此 e() 方法把寫檔動作丟到子線程執行。
為什麼用 synchronized:多條日誌可能同時觸發多個子線程寫入同一檔案,加上同步可以避免內容交錯與檔案鎖衝突。
兩個 e() 方法的分別:e(tag, msg) 用於一般除錯;e(tag, Throwable) 專門用在 try-catch 中記錄異常堆疊,標記為 [CRASH] 以便後續篩選,正式產品可將這些日誌上傳回饋。
UnknownHostException 的特殊處理:網路不通是最常見的噪音來源,直接在 getStackTraceString 中過濾掉,能讓日誌聚焦在真正的問題上。
實務建議:日誌檔會隨時間持續增大,記得加上容量上限或定期清理機制,避免佔滿使用者裝置的儲存空間。
《Android 群英傳》知識點回顧(三):控件架構、自定義 View 與事件攔截
第三章是整本書裡最「值得反覆看」的一章,因為它把 UI 的底層規則講清楚了:View 怎麼量、怎麼畫、怎麼擺放,以及觸控事件到底在誰手上流轉。以下依序回顧,並附上六個可跑
Android 應用啟動時間到底怎麼算?ThisTime、TotalTime、WaitTime 全解析
有人在社群上問過一個問題:怎麼計算一個 APK 的啟動時間?也就是從點擊桌面圖示到應用完全啟動所花的時間。已知的兩種做法——adb shell am start -w 與
有話微笑說是什麼 網絡電話怎麼打
「有話微笑說」聽名字就頗為新鮮。這款App之所以受歡迎,正是因為通話品質穩定、資費便宜,長期用下來能省下不少話費。它究竟是什麼?又該怎麼打電話?小編下面就說清楚。 有話微
Android.mk 寫錯導致 UnsatisfiedLinkError:NDK 編譯設定排查
JNI 呼叫時拋出 java.lang.UnsatisfiedLinkError,十次有九次不是 Java 程式碼的問題,而是 Android.mk 沒有把 C/C++