import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import com.hengxin.rrh.base.BaseActivity;
import com.hengxin.rxcore.utils.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
/**
* Created by fflin on 2018/12/19.
* 用於收集程序中的崩潰日誌,日誌位置 sd/01-crash/crash/crash-xxxx.txt
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
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";
private Thread.UncaughtExceptionHandler mDefaultHandler;
private Context context;
/**
* 使用Properties來保存設備的信息和錯誤堆棧信息
*/
private Properties mDeviceCrashInfo = new Properties();
public CrashHandler(Context context) {
// 獲取系統默認的UncaughtException處理器
this.context = context;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
// 如果用戶沒有處理則讓系統默認的異常處理器來處理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 退出應用 todo 這裏由自己程序控制
BaseActivity.finishAll();
Process.killProcess(Process.myPid());
}
}
/**
* 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成.
*
* @param ex
* @return true:如果處理了該異常信息;否則返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
ex.printStackTrace();
//收集設備信息
collectCrashDeviceInfo(context);
//保存錯誤報告文件
String crashFileName = saveCrashInfoToFile(ex);
Log.i("fflin","crashFileName = "+crashFileName);
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(STACK_TRACE, result);
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss");
String data = dateFormat.format(new Date());
String fileName = "crash-" + System.currentTimeMillis() + CRASH_REPORTER_EXTENSION;
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "01-crash" + File.separator + "crash" + File.separator);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream trace = new FileOutputStream(new File(file, fileName));
mDeviceCrashInfo.store(trace, "");
trace.flush();
trace.close();
return fileName;
} catch (Exception e) {
e.printStackTrace();
}
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 (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
// 使用反射來收集設備信息.在Build類中包含各種設備信息,
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
mDeviceCrashInfo.put(field.getName() + "", field.get(null) + "");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
使用方式很簡單,在application的onCreate()函數中進行初始化即可
new CrashHandler(getApplicationContext());
使用注意事項:
權限問題可能導致寫入SD卡失敗