前言:android 开发中常常会遇到程序奔溃的问题,如果不是在开发环境下,很难找到问题,这时候就需要查看日志文件,来定位问题。我所使用的方法可能不完美,但是简单,具体使用如下:
1.首先需要自定义一个application,然后继承自MultiDexApplication(使用这个的原因是有些lib里边可能出现65535限制),然后继承Thread.UncaughtExceptionHandler:
/**
1. @author xyd
*/
public class IsIpManagerApplication extends MultiDexApplication implements Thread.UncaughtExceptionHandler {
}
2.然后重写uncaughtException方法:
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
ThreadPoolManager threadPoolManager = ThreadPoolManager.getmInstance();
threadPoolManager.execute(new Runnable() {
@Override
public void run() {
saveErrorLog2Sdcard(throwable);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
}
private void saveErrorLog2Sdcard(Throwable ex) {
try {
Calendar cal = Calendar.getInstance(TimeZone
.getTimeZone("GMT+08:00"));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + ;
int day = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
File dir = new File(Constant.FOLDER_EXCEPTION);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "自定义名字.log");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file, true);
String exceptionHeader ="*************************自定义名字************";
exceptionHeader=exceptionHeader+"********************at " + year + "/"
+ month + "/" + day + " " + hour + ":" + minute + ":"
+ second + " ***************\r\n</br>";
fos.write(exceptionHeader.getBytes());
ex.printStackTrace(new PrintStream(fos));
fos.flush();
fos.close();
Log.e("自定义名字", "********************at " + year + "/" + month
+ "/" + day + " " + hour + ":" + minute + ":" + second
+ " ***************\n");
try {
PackageInfo pi = getPackageManager().getPackageInfo(
this.getPackageName(), );
exceptionHeader = exceptionHeader + "version:" + pi.versionCode
+ ",versionName:" + pi.versionName + "\n";
} catch (Exception e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ex.printStackTrace();
ex.printStackTrace(new PrintStream(baos));
exceptionHeader = exceptionHeader.replaceAll("\n", "</br>");
/*Api.getInstance(getApplicationContext()).requestNet(ApiIdConstants.APIID_UPLOADCREASHINFO, exceptionHeader,
"[email protected],[email protected]");*/
} catch (Exception e) {
e.printStackTrace();
}
}
3.最后在application的oncreate()方法中注册一下:
Thread.setDefaultUncaughtExceptionHandler(this);
这样文件就会保存在下边路径下,可以自定义路径
/**
* //项目目录的根路径
*/
public static String FOLDER_ROOT = Environment.getExternalStorageDirectory().getPath() + "/isip/";
/**
* //log所在目录
*/
public static String FOLDER_EXCEPTION = FOLDER_ROOT + "exception_log/";