App 上線之後,Android 機型五花八門,各種意料之外的崩潰都可能出现。與其讓使用者回報「它閃退了」,不如自己做一套全局捕獲機制,把裝置資訊與堆疊自動收集起來。
Java 提供了 Thread.UncaughtExceptionHandler 介面來攔截未捕獲異常,只要實作並覆寫 uncaughtException(Thread thread, Throwable ex) 即可。而 Application 是 Android 應用啟動的第一個入口,因此最適合由自訂的 Application 來擔任這個角色。
第一,在 AndroidManifest.xml 的 application 節點上宣告自己的 Application 類:
<application
android:name=".CrashApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
第二,在 onCreate 中把它設為預設異常處理器:
Thread.setDefaultUncaughtExceptionHandler(this);
第三,在 uncaughtException 中寫入處理邏輯。
public class CrashApplication extends Application implements UncaughtExceptionHandler {
private static CrashApplication INSTANCE;
private Context mContext;
private Map<String, String> info = new HashMap<String, String>();
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
public static CrashApplication getInstance() {
if (INSTANCE == null) INSTANCE = new CrashApplication();
return INSTANCE;
}
@Override
public void onCreate() {
super.onCreate();
mContext = this;
Thread.setDefaultUncaughtExceptionHandler(this);
}
public void uncaughtException(Thread thread, Throwable ex) {
collectDeviceInfo(mContext); // 收集裝置參數
saveCrashInfo2File(ex); // 落地日誌
}
/** 收集裝置與版本資訊 */
public void collectDeviceInfo(Context context) {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(
context.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
info.put("versionName",
pi.versionName == null ? "null" : pi.versionName);
info.put("versionCode", pi.versionCode + "");
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}
Field[] fields = Build.class.getDeclaredFields(); // 反射取得硬體資訊
for (Field field : fields) {
try {
field.setAccessible(true);
info.put(field.getName(), field.get("").toString());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
/** 寫入 SD 卡 crash 目錄 */
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : info.entrySet()) {
sb.append(entry.getKey() + "=" + entry.getValue() + "\r\n");
}
Writer writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
ex.printStackTrace(pw);
Throwable cause = ex.getCause();
while (cause != null) { // 逐層取出所有 cause
cause.printStackTrace(pw);
cause = cause.getCause();
}
pw.close();
sb.append(writer.toString());
long timetamp = System.currentTimeMillis();
String time = format.format(new Date());
String fileName = "crash-" + time + "-" + timetamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
File dir = new File(Environment.getExternalStorageDirectory(), "crash");
if (!dir.exists()) dir.mkdir();
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
把日誌寫到外部儲存需要授權,新版 Android 還要留意 scoped storage 的限制,可改寫到 App 專屬目錄。另外捕獲後若要重啟 App,記得留一點延遲並啟動原 Activity,避免流程被打斷;正式上線時也建議把日誌上報到後端,而不是只留在本機。