错误日志

   错误日志有利于测试时程序崩溃时,能通过错误日志直接找到问题所在,就不用麻烦的问题复现了.首先我们创建个错误捕捉类,代码如下:

import java.lang.Thread.UncaughtExceptionHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.os.Build;
import android.os.Environment;

/**
 * UncaughtException处理类,当程序发生Uncaught异常的时候,有该类来接管程序,并记录发送错误报告.
 * 
 * @author
 * 
 */
public class CrashHandler implements UncaughtExceptionHandler {

	// 系统默认的UncaughtException处理类
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	public static final String BASE_PATH = Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/LockScreenGrid/";
	public static final String BASE_ERROR_PATH = BASE_PATH + "errorlog/";
	// CrashHandler实例
	private static CrashHandler INSTANCE = new CrashHandler();

	private CrashHandler() {
	}

	/** 获取CrashHandler实例 ,单例模式 */
	public static CrashHandler getInstance() {
		return INSTANCE;
	}

	/**
	 * 初始化
	 * 
	 * @param context
	 */
	public void start() {
		// 获取系统默认的UncaughtException处理器
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		// 设置该CrashHandler为程序的默认处理器
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	/**
	 * 当UncaughtException发生时会转入该函数来处理
	 */
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			// 如果用户没有处理则让系统默认的异常处理器来处理
			mDefaultHandler.uncaughtException(thread, ex);
		} else {
			// 退出程序
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
		}
	}

	private boolean handleException(Throwable e) {
		if (e != null) {
			StringBuffer sb = new StringBuffer();
			DateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss",
					Locale.getDefault());
			String time = formatter
					.format(new Date(System.currentTimeMillis()));
			sb.append("Time: " + time);
			sb.append("\n");
			sb.append("Phone :" + Build.MODEL);
			sb.append("\n");
			sb.append("Exception: " + FileUtils.getExceptionMsg(e));

			String fileName = "crash-" + time + ".txt";
			FileUtils.writeStringToFile(sb.toString(), BASE_ERROR_PATH
					+ fileName);
			return true;
		}
		return false;
	}

}

然后我们需要的一些创建文件的工具了,代码如下:

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import android.util.Log;

public class FileUtils {
	public static boolean createFile(String path) {
		File file = new File(path);
		File parent = file.getParentFile();
		if (parent != null && !parent.exists()) {
			parent.mkdirs();
		}
		if (file.exists()) {
			file.delete();
		}
		try {
			return file.createNewFile();
		} catch (IOException e) {
			Log.e("FileUtils", "文件创建失败");
			return false;
		}
	}
	public static String getExceptionMsg(Throwable e) {
		String msg = null;
		Writer writer = null;
		PrintWriter pw = null;
		try {
			writer = new StringWriter();
			pw = new PrintWriter(writer);
			e.printStackTrace(pw);
			Throwable cause = e.getCause();
			while (cause != null) {
				cause.printStackTrace(pw);
				cause = cause.getCause();
			}
			msg = writer.toString();
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			closeStream(pw);
			closeStream(writer);
		}
		return msg;
	}
	public static void writeStringToFile(String msg, String path) {
		if (!createFile(path)) {
			return;
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(path);
			fos.write(msg.getBytes());
		} catch (Exception e) {
			Log.e("FileUtils", "writeStringToFile error");
		} finally {
			closeStream(fos);
		}
	}
	public static void closeStream(Closeable stream) {
		try {
			if (stream != null) {
				stream.close();
			}
		} catch (Exception e) {
		}
	}
}


接下来我们在程序启动时启动我们的捕获错误类,代码如下:

import com.example.textdemo.Util.CrashHandler;

import android.app.Application;

public class App extends Application {
	@Override
	public void onCreate() {
		// 捕捉异常
		CrashHandler.getInstance().start();
	}
}

我们要在清单文件中把Application中的name引用我们的App,

 <application
        android:name="com.example.textdemo.App"
这样我们的任务就完成了.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值