android应用异常退出,抓取异常信息写入文件里

直接上代码,想用的同学直接创建一个类就可以用了!

/**
 * 程序异常抓包
 * 
 * @author MarsKang
 * 
 */
public class CrashHandler implements UncaughtExceptionHandler {
	public static final String TAG = "CrashHandler";
	private static CrashHandler INSTANCE = new CrashHandler();
	private Context mContext;
	private Thread.UncaughtExceptionHandler mDefaultHandler;

	private CrashHandler() {
	}

	public static CrashHandler getInstance() {
		return INSTANCE;
	}

	public void init(Context ctx) {
		mContext = ctx;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(final Thread thread, final Throwable ex) {
		// TODO Auto-generated method stub
		if (!handleException(ex) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else { // 如果自己处理了异常,则不会弹出错误对话框,则需要手动退出app
			new Thread() {
				@Override
				public void run() {
					Looper.prepare();
					new AlertDialog.Builder(mContext).setTitle("提示")
							.setCancelable(false).setMessage("程序崩溃了...")
							.setNeutralButton("我知道了", new OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									mDefaultHandler.uncaughtException(thread, ex);
								}
							}).create().show();
					Looper.loop();
				}
			}.start();
		}
	}

	/**
	 * 自定义错误处理
	 */
	private boolean handleException(final Throwable ex) {
		if (ex == null) {
			return true;
		}
		Util.e(TAG, "异常退出,错误信息已存入SDCARD");
		new Thread() {
			@Override
			public void run() {
				String fileName = "Crash_" + Util.getCurrentDate("yyyy_MM_dd_HH_mm_ss") + ".log"; //这里创建文件名
				File file = new File(Environment.getExternalStorageDirectory(),
						fileName);
				try {
					FileOutputStream fos = new FileOutputStream(file, true);
					fos.write(formatStackTrace(ex).getBytes());
					fos.flush();
					fos.close();
				} catch (Exception e) {
				}
			}
		}.start();
		return true;
	}
	
	/***
	 * 格式化堆栈信息
	 */
	public String formatStackTrace(Throwable throwable) {  
	    if(throwable==null) return "";  
	    String rtn = throwable.getStackTrace().toString();  
	    try {  
	        Writer writer = new StringWriter();  
	        PrintWriter printWriter = new PrintWriter(writer);  
	        throwable.printStackTrace(printWriter);       
	        printWriter.flush();  
	        writer.flush();  
	        rtn = writer.toString();  
	        printWriter.close();              
	        writer.close();  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } catch (Exception ex) {  
	    }  
	    return rtn;  
	} 
}
在主activity,onCreate()里注册捕获异常

//初始化异常捕获
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(this);




你可能感兴趣的:(android)