Android市场品牌多样,一些比较强势的公司都定制了自己的系统,所以在开发过程中就算很严密的测试还是会遇到一些漏网之鱼,所以开发应用的全局异常 捕捉处理是一项重要的工作,以便我们及时发现问题并处理。其实安卓默认了一个UncaughtException处理类,我们只需继承该类并收集信息及时处理。
/**
* 异常处理类,继承UncaughtException处理类
*
* Created by wk
*/
public class MyCrashHandler implements UncaughtExceptionHandler {
private UncaughtExceptionHandler crashHandler;
private Context mContext;
private static MyCrashHandler INSTANCE = new MyCrashHandler();
/**
* 单例模式,保证只有一个CrashHandler实例
*/
private MyCrashHandler() {
}
public static MyCrashHandler getInstance() {
return INSTANCE;
}
/**
* 初始化
*
* @param context
*/
public void init(Context context) {
mContext = context;
crashHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 重写方法,异常发生时调用
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!dealException(ex) && crashHandler != null) {
crashHandler.uncaughtException(thread, ex);
}
}
/**
* 收集设备参数信息
*
* @param context
*/
public Map<String, String> collectDeviceInfo(Context context) {
Map<String, String> infos = new HashMap<String, String>();
try {
PackageManager pManager = context.getPackageManager();
PackageInfo pInfo = pManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pInfo != null) {
String versionName = "";
if (versionName == null) {
versionName = null;
} else {
versionName = pInfo.versionName;
}
String versionCode = pInfo.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
} catch (Exception e) {
}
}
return infos;
}
/**
* 保存错误信息到文件中
*
* @param ex
* @return 返回文件名称, 便于将文件传送到服务器
*/
public void saveCrashInfo2File(Throwable ex, Map<String, String> infos) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = DateUtil.long2string(timestamp, DateUtil.YYYY_MM_DD_HH_MM);
String fileName = "crash-" + time + "-" + timestamp + ".txt";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = FileUtils.getInstance().getSDPATHWork() + "crash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
postReport(fileName, path + fileName);
fos.close();
}
} catch (Exception e) {
}
}
/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean dealException(Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
@Override
public void run() {
Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出", Toast.LENGTH_LONG).show();
}
}.start();
Map<String, String> infos = collectDeviceInfo(mContext);
saveCrashInfo2File(ex, infos);
return true;
}
private void postReport(String fileName, String resFile) {
}
}
该类中收集信息文件的命名可根据自己的需要进行修改,上传的方法也根据自己对应服务器的路径进行操作,此处省略。
在application类中初始化全局异常捕捉实例即可。
/**
* Created by wk
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MyCrashHandler crashHandler = MyCrashHandler.getInstance();
crashHandler.init(getApplicationContext());
}
}