今天測試遇到崩潰,而我又沒辦法查看,於是老司機教了我一招。
下面是CrashHandler類:
package com.bbk.bfcupload.bfcuploadtestdemo.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import com.eebbk.bfc.uploadsdk.uploadmanage.LogUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* UncaughtException處理類,當程序發生Uncaught異常的時候,由該類來接管程序,並記錄發送錯誤報告.
*
* @author way
*/
public class CrashHandler implements UncaughtExceptionHandler {
private Context mContext;
private UncaughtExceptionHandler mDefaultHandler; // 系統默認的UncaughtException處理類
private static CrashHandler INSTANCE = new CrashHandler(); // CrashHandler實例
private Map<String, String> info = new HashMap<String, String>(); // 用來存儲設備信息和異常信息
/**
* 保證只有一個CrashHandler實例
*/
private CrashHandler() {
}
/**
* 獲取CrashHandler實例 ,單例模式
*/
public static CrashHandler getInstance() {
return INSTANCE;
}
/**
* 初始化
*
* @param context
*/
public void init(Context context) {
mContext = context.getApplicationContext();
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 獲取系統默認的UncaughtException處理器
Thread.setDefaultUncaughtExceptionHandler(this);// 設置該CrashHandler爲程序的默認處理器
}
/**
* 當UncaughtException發生時會轉入該重寫的方法來處理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (mDefaultHandler != null) {
handleException(ex);// 如果自定義的沒有處理則讓系統默認的異常處理器來處理
mDefaultHandler.uncaughtException(thread, ex);// 退出程序
android.os.Process.killProcess(android.os.Process.myPid());
}
}
/**
* 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成.
*
* @param ex 異常信息 <a
* href="\"http://www.eoeandroid.com/home.php?mod=space&uid=7300\""
* target="\"_blank\"">@return</a> true 如果處理了該異常信息;否則返回false.
*/
public boolean handleException(final Throwable ex) {
if (ex == null) return false;
LogUtils.e(ex, " uncaught exception !");
// 收集設備參數信息
collectDeviceInfo(mContext);
// 保存日誌文件
final String exString = getCrashInfoString(ex);
saveCrashInfo2File(exString, mContext);
return true;
}
/**
* 收集設備參數信息
*
* @param context
*/
public void collectDeviceInfo(Context context) {
try {
PackageManager pm = context.getPackageManager();// 獲得包管理器
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);// 得到該應用的信息,即主Activity
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
info.put("versionName", versionName);
info.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
LogUtils.e("Error: " + e);
}
Field[] fields = Build.class.getDeclaredFields();// 反射機制
for (Field field : fields) {
try {
field.setAccessible(true);
info.put(field.getName(), field.get("").toString());
} catch (IllegalArgumentException e) {
LogUtils.e("Error: " + e);
} catch (IllegalAccessException e) {
LogUtils.e("Error: " + e);
}
}
}
private String getCrashInfoString(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : info.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key).append("=").append(value).append("\r\n");
}
Writer writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
ex.printStackTrace(pw);
Throwable cause = ex.getCause();
// 循環着把所有的異常信息寫入writer中
while (cause != null) {
cause.printStackTrace(pw);
cause = cause.getCause();
}
pw.close();// 記得關閉
String result = writer.toString();
sb.append(result);
return sb.toString();
}
@SuppressLint("SimpleDateFormat")
public static String saveCrashInfo2File(String exString, Context context) {
long timetamp = System.currentTimeMillis();
String time = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
String fileName = "-crash-" + time + "-" + timetamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
//File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "SynChinese");
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + ".crash" + File.separator + context.getPackageName());
if (!dir.exists()) {
dir.mkdirs();
}
File outfile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outfile);
fos.write(exString.getBytes());
fos.close();
return outfile.getAbsolutePath();
} catch (FileNotFoundException e) {
LogUtils.e("Error: " + e);
} catch (IOException e) {
LogUtils.e("Error: " + e);
}
}
return null;
}
}
在application裏面調用:
CrashHandler.getInstance().init(this);
則遇到崩潰時會自動創建.crash文件,不過文件不可見的需要用文件管理器纔可以