在日常開發(fā)中會經(jīng)常遇到程序崩潰現(xiàn)象,但是又難以抓取log,導致了無法排除問題點,所以就需要這個類去拯救你的程序啦!
public class LauncherCrashHandler implements UncaughtExceptionHandler {
/** Debug Log tag*/
public static final String TAG = LauncherCrashHandler.class.getSimpleName();
/** 是否開啟日志輸出,在Debug狀態(tài)下開啟,
* 在Release狀態(tài)下關閉以提升程序性能
* */
public static final boolean DEBUG = false;
/** 系統(tǒng)默認的UncaughtException處理類 */
private UncaughtExceptionHandler mDefaultHandler;
/** CrashHandler實例 */
private static volatile LauncherCrashHandler 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 = ".txt";
/** 保證只有一個CrashHandler實例 */
private LauncherCrashHandler() {}
/** 獲取CrashHandler實例 ,單例模式*/
public static LauncherCrashHandler getInstance() {
if (INSTANCE == null) {
synchronized (LauncherCrashHandler.class) {
if (INSTANCE == null) {
INSTANCE = new LauncherCrashHandler();
}
}
}
return INSTANCE;
}
/**
* 初始化,注冊Context對象,
* 獲取系統(tǒng)默認的UncaughtException處理器,
* 設置該CrashHandler為程序的默認處理器
* @param ctx
*/
public void init(Context ctx) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 當UncaughtException發(fā)生時會轉(zhuǎn)入該函數(shù)來處理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果用戶沒有處理則讓系統(tǒng)默認的異常處理器來處理
mDefaultHandler.uncaughtException(thread, ex);
} else {
//Sleep一會后結束程序
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.d(TAG, e.toString());
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
private void showToast(String message){
final String msg = message;
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast toast = Toast.makeText(mContext, "程序出錯,即將退出:\r\n" + msg,
Toast.LENGTH_LONG);
Log.d("nh",msg);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Looper.loop();
}
}.start();
}
/**
* 自定義錯誤處理,收集錯誤信息
* 發(fā)送錯誤報告等操作均在此完成.
* 開發(fā)者可以根據(jù)自己的情況來自定義異常處理邏輯
* @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;
}
//使用Toast來顯示異常信息
//showToast(msg);
//收集設備信息
collectCrashDeviceInfo(mContext);
//保存錯誤報告文件
saveCrashInfoToFile(ex);
//發(fā)送錯誤報告到服務器
//sendCrashReportsToServer(mContext);
return true;
}
/**
* 在程序啟動時候, 可以調(diào)用該函數(shù)來發(fā)送以前沒有發(fā)送的報告
*/
public void sendPreviousReportsToServer() {
sendCrashReportsToServer(mContext);
}
/**
* 把錯誤報告發(fā)送給服務器,包含新產(chǎn)生的和以前沒發(fā)送的.
* @param ctx
*/
private void sendCrashReportsToServer(Context ctx) {
String[] crFiles = getCrashReportFiles(ctx);
if (crFiles != null && crFiles.length > 0) {
TreeSet<String> sortedFiles = new TreeSet<String>();
sortedFiles.addAll(Arrays.asList(crFiles));
for (String fileName : sortedFiles) {
File cr = new File(ctx.getFilesDir(), fileName);
postReport(cr);
cr.delete();// 刪除已發(fā)送的報告
}
}
}
private void postReport(File file) {
// TODO 發(fā)送錯誤報告到服務器
}
/**
* 獲取錯誤報告文件名
* @param ctx
* @return
*/
private String[] getCrashReportFiles(Context ctx) {
File filesDir = ctx.getFilesDir();
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(CRASH_REPORTER_EXTENSION);
}
};
return filesDir.list(filter);
}
/**
* 保存錯誤信息到文件中
* @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();
showToast(result);
printWriter.close();
mDeviceCrashInfo.put("EXEPTION", ex.getLocalizedMessage());
mDeviceCrashInfo.put(STACK_TRACE, result);
final StringBuffer sb = new StringBuffer();
for (Entry<Object, Object> entry: mDeviceCrashInfo.entrySet()) {
sb.append(entry.getKey()+" = "+entry.getValue());
sb.append("\n");
}
try {
//long timestamp = System.currentTimeMillis();
Time t = new Time("GMT+8");
t.setToNow(); // 取得系統(tǒng)時間
int date = t.year * 10000 + t.month * 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.write(sb.toString().getBytes());
//trace.flush();
trace.close();
return fileName;
} catch (Exception e) {
Log.d(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);
}
//使用反射來收集設備信息.在Build類中包含各種設備信息,
//例如: 系統(tǒng)版本號,設備生產(chǎn)商 等幫助調(diào)試程序的有用信息
//具體信息請參考后面的截圖
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);
}
}
}
}