import java.lang.Thread.UncaughtExceptionHandler;
import android.content.Context;
import android.content.pm.PackageInfo;
import com.ddsc.fincar.util.AppInfoUtils;
/**
*
* @ClassName AppException
* @Description 应用程序异常类:用于处理程序异常
*
*/
public class AppException extends Exception implements UncaughtExceptionHandler {
private byte type;
private int code;
/** 系统默认的UncaughtException处理类 */
private UncaughtExceptionHandler mDefaultHandler;
private AppException() {
this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
}
private AppException(byte type, int code, Exception excp) {
super(excp);
this.type = type;
this.code = code;
}
public int getCode() {
return this.code;
}
public int getType() {
return this.type;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
}
}
/**
* 自定义异常处理:收集错误信息&发送错误报告
*
* @param ex
* @return true:处理了该异常信息;否则返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
final Context context = AppManager.getAppManager().currentActivity();
if (context == null) {
return false;
}
final String crashReport = getCrashReport(context, ex);
// 发送崩溃日志
SendErrorLogPostRequest logRequest = new SendErrorLogPostRequest(
context, new HttpRequestListener(){});
logRequest.setLoadingVisible(false);
logRequest.setRequestParams(crashReport);
HttpRequestQueue.addToRequestQueue(context, logRequest);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
AppManager.getAppManager().AppExit(context);
android.os.Process.killProcess(android.os.Process.myPid());
return true;
}
/**
* 获取APP崩溃异常报告
*
* @param ex
* @return
*/
private String getCrashReport(Context context, Throwable ex) {
PackageInfo pinfo = AppInfoUtils.getPackageInfo(context);
StringBuffer exceptionStr = new StringBuffer();
exceptionStr.append("Version: " + pinfo.versionName + "("
+ pinfo.versionCode + ")\n");
exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE
+ "(" + android.os.Build.MODEL + ")\n");
exceptionStr.append("Exception: " + ex.getMessage() + "\n");
StackTraceElement[] elements = ex.getStackTrace();
for (int i = 0; i < elements.length; i++) {
exceptionStr.append(elements[i].toString() + "\n");
}
Throwable cause = ex.getCause();
if(cause != null){
exceptionStr.append("Cause By: " + cause.getMessage() + "\n");
StackTraceElement[] causenots = cause.getStackTrace();
for (int i = 0; i < causenots.length; i++) {
exceptionStr.append(causenots[i].toString() + "\n");
}
}
return exceptionStr.toString();
}
/**
* 获取APP异常崩溃处理对象
* @param
* @return
*/
public static AppException getAppExceptionHandler(){
return new AppException();
}
}
application中需要Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());