android自定义异常处理与错误日志上传

android自定义异常处理与错误日志上传

使用场景

1.作为一个android开发者,我们在使用真机调试的时候如果不建立adb连接是很难查看程序报出的错误信息的,我们通过使用此方法可以将错误日志捕获并且存储到本地或者上传到服务器。


2.当我们的应用程序上线,可能会因为机型问题导致我们的程序出现问题,我们可以通过此方法来将错误日志上传到我们服务器上,通过查看日志来使我们不断的完善我们的APP


代码实现

一般在application中调用此方法

Thread.setDefaultUncaughtExceptionHandler(AppException.getAppExceptionHandler());  


异常处理的主类

/**
 * @Description 应用程序异常类:用于捕获异常和提示错误信息
 * @author lhn
 * @created 2016-5-21
 */
public class AppException extends Exception implements UncaughtExceptionHandler {

	private static final long serialVersionUID = 1L;

	/** 系统默认的UncaughtException处理类 */
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	
	/** 无参的构造函数 */
	private AppException() {
		this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
	}

	/** 有参的构造函数 */
	private AppException(Exception excp) {
		super(excp);
		this.saveErrorLog(excp);
	}

	/**
	 * @Description 保存异常日志
	 * 
	 * @param Exception
	 *            excp(异常日志)
	 */
	public void saveErrorLog(Exception excp) {
		//定义错误日志文件存储信息
		String errorlog = "errorlog.txt";
		String savePath = "";
		String logFilePath = "";
		//文件输出
		FileWriter fw = null;
		PrintWriter pw = null;
		
		try {
			// 判断是否挂载了SD卡
			String storageState = Environment.getExternalStorageState();
			if (storageState.equals(Environment.MEDIA_MOUNTED)) {
				//设置存储路径
				savePath = Environment.getExternalStorageDirectory()
						.getAbsolutePath() + "/OSChina/Log/";
				//实例化File
				File file = new File(savePath);
				
				if (!file.exists()) {
					//创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。
					file.mkdirs();
				}
				
				//日志路径
				logFilePath = savePath + errorlog;
			}
			// 没有挂载SD卡,无法写文件
			if (logFilePath == "") {
				return;
			}
			//实例化logFile
			File logFile = new File(logFilePath);
			//判断是否已经存在
			if (!logFile.exists()) {
				logFile.createNewFile();
			} else {
				logFile.delete();
				logFile.createNewFile();
			}
			//实例化文件输出
			fw = new FileWriter(logFile, true);
			pw = new PrintWriter(fw);
			//在命令行打印异常信息在程序中出错的位置及原因
			excp.printStackTrace(pw);
			//释放资源
			pw.close();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pw != null) {
				pw.close();
			}
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
				}
			}

		}
		//结束此错误Activity
		ActivityCollector.finishAll();
	}

	/**
	 * @Description 获取APP异常崩溃处理对象
	 * 
	 * @return AppException
	 */
	public static AppException getAppExceptionHandler() {
		return new AppException();
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {

		//如果异常没有被处理
		if (!handleException(ex) && mDefaultHandler != null) {
			//进行异常捕获
			mDefaultHandler.uncaughtException(thread, ex);
		}

	}

	/**
	 * @Description 自定义异常处理:收集错误信息&发送错误报告
	 * 
	 * @param Throwable
	 *            ex(异常信息)
	 * @return true:处理了该异常信息;否则返回false
	 */
	private boolean handleException(Throwable ex) {
		if (ex == null) {
			return false;
		}
		// APP崩溃异常报告
		final String crashReport = getCrashReport(
				OneLeadPosApplication.getOneLeadPosApplication(), ex);

		// 错误信息存储到本地
		saveErrorLog((Exception) ex);

		// 显示异常信息&发送报告(上传到服务器)
		// new Thread() {
		// public void run() {
		// Looper.prepare();
		// UIHelper.sendAppCrashReport(context, crashReport);
		// Looper.loop();
		// }
		//
		// }.start();
		
		return true;
	}

	/**
	 * @Description 获取APP崩溃异常报告
	 * 
	 * @param Context
	 *            context(上下文), Throwable ex(异常信息)
	 * @return String
	 */
	private String getCrashReport(Context context, Throwable ex) {

		StringBuffer exceptionStr = new StringBuffer();
		// android版本以及系统型号
		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");
		}
		// 返回组成的StringBuffer
		return exceptionStr.toString();
	}
}

你可能感兴趣的:(android开发之工作篇,android错误日志上传,异常捕获,自定义异常处理,调试)