android框架搭建(一)-基本工具[log]的建立
log 作爲統一tag的日誌輸出,對於高質量的代碼事非常重要的:
- 在開發中保持所有開發人員輸出log格式一致便於閱讀
- 便於快速發現bug
- 由於log打印日誌非常耗費CPU,所以程序在運行或者項目開發的不同階段的時候只需要選擇打印自己需要的那一部分日誌,來降低CPU耗費
- 考慮線上安全,避免日誌被非法抓取
- 保存錯誤信息到棧
話不多說上代碼:
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.text.format.Time;
import android.util.Log;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.util.Properties;
public class CrashHandler implements UncaughtExceptionHandler {
/** Debug Log tag */
public static final String TAG = "CrashHandler";
/**
* 是否開啓日誌輸出,在Debug狀態下開啓, 在Release狀態下關閉以提示程序性能
* */
public static final boolean DEBUG = false;
/** 系統默認的UncaughtException處理類 */
private UncaughtExceptionHandler mDefaultHandler;
/** CrashHandler實例 */
private static CrashHandler INSTANCE;
/** 程序的Context對象 */
private Context mContext;
/** 使用Properties來保存設備的信息和錯誤堆棧信息 */
private Properties mDeviceCrashInfo = new Properties();
private static final String VERSION_NAME = "versionName";
private static final String VERSION_CODE = "versionCode";
private static final String STACK_TRACE = "STACK_TRACE";
/** 錯誤報告文件的擴展名 */
private static final String CRASH_REPORTER_EXTENSION = ".cr";
/** 保證只有一個CrashHandler實例 */
private CrashHandler() {
}
/** 獲取CrashHandler實例 ,單例模式 */
public static CrashHandler getInstance() {
if (INSTANCE == null) {
INSTANCE = new CrashHandler();
}
return INSTANCE;
}
/**
* 初始化,註冊Context對象, 獲取系統默認的UncaughtException處理器, 設置該CrashHandler爲程序的默認處理器
*
* @param ctx
*/
public void init(Context ctx) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 當UncaughtException發生時會轉入該函數來處理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
mContext.sendBroadcast(new Intent(IntentAction.EXIT_APPLICATION));
if ( mDefaultHandler != null) {
handleException(ex);
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(TAG, "Error : ", e);
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
/**
* 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成. 開發者可以根據自己的情況來自定義異常處理邏輯
*
* @param ex
* @return true:如果處理了該異常信息;否則返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
Log.w(TAG, "handleException --- ex==null");
return true;
}
final String msg = ex.getLocalizedMessage();
if (msg == null) {
return false;
}
collectCrashDeviceInfo(mContext);
saveCrashInfoToFile(ex);
return true;
}
/**
* 保存錯誤信息到文件中
*
* @param ex
* @return
*/
private String saveCrashInfoToFile(Throwable ex) {
Writer info = new StringWriter();
PrintWriter printWriter = new PrintWriter(info);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
String result = info.toString();
printWriter.close();
mDeviceCrashInfo.put("EXEPTION", ex.getLocalizedMessage());
mDeviceCrashInfo.put(STACK_TRACE, result);
try {
Time t = new Time("GMT+8");
t.setToNow();
int date = t.year * 10000 + (t.month + 1) * 100 + t.monthDay;
int time = t.hour * 10000 + t.minute * 100 + t.second;
String fileName = "crash-" + date + "-" + time
+ CRASH_REPORTER_EXTENSION;
FileOutputStream trace = mContext.openFileOutput(fileName,
Context.MODE_PRIVATE);
mDeviceCrashInfo.store(trace, "");
trace.flush();
trace.close();
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing report file...", e);
}
return null;
}
/**
* 收集程序崩潰的設備信息
*
* @param ctx
*/
public void collectCrashDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),
PackageManager.GET_ACTIVITIES);
if (pi != null) {
mDeviceCrashInfo.put(VERSION_NAME,
pi.versionName == null ? "not set" : pi.versionName);
mDeviceCrashInfo.put(VERSION_CODE, "" + pi.versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "Error while collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
mDeviceCrashInfo.put(field.getName(), "" + field.get(null));
if (DEBUG) {
Log.d(TAG, field.getName() + " : " + field.get(null));
}
} catch (Exception e) {
Log.e(TAG, "Error while collect crash info", e);
}
}
}
}