前言: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/";