Android记录程序崩溃Log写入文件

分享到:
将导致程序崩溃的堆栈调用Log写入文件,便于收集bug。在调试安卓程序,由于某些原因调试时手机不能连接PC端,无法通过IDE查看程序崩溃的Log,希望log能够写入文件中,对于已经发布的App可以通过该功能收集Bug。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
public class MyCrashHandler implements UncaughtExceptionHandler{
private static MyCrashHandler crashHandler;
@Override
	public void uncaughtException(Thread thread, Throwable ex) {
// TODO Auto-generated method stub
if (crashHandler != null) {
try {
//将crash log写入文件
FileOutputStream fileOutputStream = new FileOutputStream("/mnt/sdcard/crash_log.txt", true);
PrintStream printStream = new PrintStream(fileOutputStream);
ex.printStackTrace(printStream);
printStream.flush();
printStream.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
	}
//设置默认处理器
	public void init() {
Thread.setDefaultUncaughtExceptionHandler(this);
	}
private MyCrashHandler() {}
//单例
	public static MyCrashHandler instance() {
if (crashHandler == null) {
synchronized (crashHandler) {
crashHandler = new MyCrashHandler();
}
}
return crashHandler;
	}
}
昵    称:
验证码:

相关文档: