android 处理程序crash日志

本文介绍如何通过Java的UncaughtExceptionHandler接口实现全局异常捕捉并记录日志的方法。通过自定义CrashHandler类,可以在程序崩溃时创建日志文件并详细记录异常信息,便于后续的故障排查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

          日志是为了方便记录程序的各种异常情况,方便以后对程序的维护的修补,一个程序不可能做到百分百健壮和完美,所以有必要在代码中保存日志,方便维护。Java线程类提供了一个接口UncaughtExceptionHandler,Thread.setDefaultUncaughtExceptionHandler(handler)设置当线程由于未捕获到异常而突然终止,并且没有为该线程定义其他处理程序时所调用的默认处理程序。

   所以我们可以继承UncaughtExceptionHandler, 在handler实现对日志的读写

  

   public class CrashHandler implements UncaughtExceptionHandler {
	// 系统默认的UncaughtException处理
	private Thread.UncaughtExceptionHandler mDefaultHandler;

	public CrashHandler() {
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		try {
			// 创建日志文件
			File file = createCreashLogFile();

			// 写入日志文件
			if (file != null && file.exists()) {
				writeLog(file, ex);
			}
		} catch (Exception e) {
		    LogUtils.w("", e);
		}

		// 将异常抛给系统处�?
		mDefaultHandler.uncaughtException(thread, ex);
	}

	private void writeLog(File logFile, Throwable ex) {
		PrintStream printStream = null;
		FileOutputStream fos = null;

		// 写入日志文件
		try {
			fos = new FileOutputStream(logFile);
			printStream = new PrintStream(fos);
			ex.printStackTrace(printStream);
		} catch (Exception e) {
		    LogUtils.w("", e);
		} finally {
			closeQuietly(printStream);
			closeQuietly(fos);
		}
	}

	private void closeQuietly(OutputStream os) {
		if (os != null) {
			try {
				os.close();
			} catch (IOException e) {
			    LogUtils.w("", e);
			}
		}
	}

	/** 创建�?个空白的崩溃日志文件 */
	public static File createCreashLogFile() throws IOException {
		if (!isExternalStorageAvaliable()) { // �?查存储是否可�?
			return null;
		}

		File directory = new File(Environment.getExternalStorageDirectory()
				+ "/ViolationQuery/crash_log");
		if (!directory.exists()) {
			directory.mkdirs();
		}
		File file = new File(directory, createCrashLogFileName());
		if (file.exists()) {
			file.delete();
		}
		file.createNewFile();

		return file;
	}

	/** 存储是否可用 */
	public static boolean isExternalStorageAvaliable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		} else {
			return false;
		}
	}

	private static String createCrashLogFileName() {
		String dateString = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		return "CrashLog_" + dateString + ".txt";
	}
}
<pre name="code" class="java">public class CrashManager {
	public static void start() {
		// 设置异常处理实例
		CrashHandler handler = new CrashHandler();
		Thread.setDefaultUncaughtExceptionHandler(handler);
	}
}



 然后在Application中调用Application中CrashManager.start();这样就大功告成了

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值