本身定义一个用于捕获全局异常的类,继承自 Thread.UncaughtException:java
给此类(CrashHandler)设计一个单例:
android
继承UncaughtException后实现 uncaughtException(Thread thread, Throwable ex) 方法服务器
自定义抓取异常的处理操做: handleException(Throwable ex)
app
代码以下:ide
public class CrashHandler implements Thread.UncaughtExceptionHandler { private static final String TAG = "CrashHandler"; private Thread.UncaughtExceptionHandler defaultHandler; private Context context; private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); //用来存储设备信息和异常信息 private Map<String, String> infos = new HashMap<String, String>(); //建立CrashHandler实例(单例模式); private static CrashHandler instance = new CrashHandler(); public static CrashHandler getInstance() { return instance; } /** * 私有化构造器保证只有一个对象 */ private CrashHandler() { } /** * 初始化 * * @param context */ public void init(Context context) { this.context = context; //获取系统默认的uncaughtException处理器 defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); //设置crashhandler为程序默认的处理器 Thread.setDefaultUncaughtExceptionHandler(this); } /** * 当UncaughtException发生时会转入该函数来处理 * * @param thread * @param ex */ @Override public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && defaultHandler != null) { //若是用户没有处理则让系统默认的异常处理器来处理 defaultHandler.uncaughtException(thread, ex); }else { try { Thread.sleep(3000); } catch (InterruptedException e) { Log.e(TAG, "uncaughtException: error",e ); } //退出程序 Process.killProcess(0); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(1);//非正常退出; } } /** * 自定义错误处理,手机错误信息,发送错误拔高等操做均在此完成 * * @param ex * @return true; 若是处理了该异常信息; 不然返回false */ private boolean handleException(Throwable ex) { if (ex == null) { return false; } //使用Toast来显示异常信息 new Thread() { @Override public void run() { Looper.prepare(); Toast.makeText(context, "很抱歉,程序出现异常,即将退出", Toast.LENGTH_SHORT).show(); Looper.loop(); } }.start(); //手机设备参数信息; collectDeviceInfo(context); //保存日志文件: saveCrashInfo2File(ex); return true; } /** * 保存错误信息到文件中 * @param ex * @return 返回文件名称,便于将文件传送到服务器 */ private String saveCrashInfo2File(Throwable ex) { 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); String fileName = null; try { long timestamp = System.currentTimeMillis(); String time = dateFormat.format(new Date()); fileName = "crash-" + time + "-" + timestamp + ".loge"; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String path = "/sdcard/crash/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } FileOutputStream fos = new FileOutputStream(path + fileName); fos.write(sb.toString().getBytes()); fos.close(); } return fileName; } catch (IOException e) { Log.e(TAG, "saveCrashInfo2File: an error occured while writing file", e); } return null; } /** * 手机设备参数信息 * * @param context */ private void collectDeviceInfo(Context context) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); if (packageInfo != null) { String versinName = packageInfo.versionName == null ? "null" : packageInfo.versionName; String versionCode = packageInfo.versionCode + ""; infos.put("versionName", versinName); infos.put("versionCode", versionCode); } } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "an error occored when collect package info", e); } Field[] declaredFields = Build.class.getDeclaredFields(); for (Field field : declaredFields) { try { field.setAccessible(true); infos.put(field.getName(), field.get(null).toString()); Log.d(TAG, field.getName() + ":" + field.get(null)); } catch (IllegalAccessException e) { Log.e(TAG, "collectDeviceInfo: an error occured when collect crash info", e); } } } }
固然不要忘了在Application里面初始化:函数
App Application { onCreate() { .onCreate(); CrashHandler crashHandler = CrashHandler.(); crashHandler.init(getApplicationContext()); } }
记得在menifest.xml给App添加 name
oop
文章转自 http://blog.csdn.net/jdsjlzx/article/details/7606423
ui