在android開發(fā)中圣拄,在用戶正常使用的情況下绅你,需要定位到用戶在使用過(guò)程中出現(xiàn)的崩潰原因纪岁,通常會(huì)將崩潰日志寫入手機(jī)本地文件中凑队,從而有利于發(fā)現(xiàn)并解決問(wèn)題。
我們通常會(huì)實(shí)現(xiàn)Thread.UncaughtExceptionHandler接口來(lái)捕獲到異常信息幔翰,將異常信息寫入本地文件漩氨。
1.關(guān)于權(quán)限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2.通過(guò)傳入?yún)?shù)application進(jìn)行初始化
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(this);
好了,不用管了遗增。
FileConstant.java
/**
* 【說(shuō)明】:文件操作常量
*
*/
public class FileConstant {
/**
* 應(yīng)用基礎(chǔ)文件夾名稱
*/
public static final String APP_BASE_DIR_NAME = "AppNamexx";
/**
* 應(yīng)用日志文件夾名稱
*/
public static final String APP_LOG_DIR_NAME = "Log";
/**
* 應(yīng)用崩潰日志文件夾名稱
*/
public static final String APP_LOG_CRASH_DIR_NAME = "Crash";
}
FileUtil.java
/**
* 【說(shuō)明】:文件及文件夾工具類
*/
public class FileUtil {
private static final String TAG = "FileUtil";
/**
* 【說(shuō)明】:獲取手機(jī)存儲(chǔ)空間文件夾
*
* @param context 上下文
* @return File 文件夾(/storage/emulated/0或/data/user/0/(packageName))
*/
private static File getAppDir(Context context) {
String appDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//獲取外部存儲(chǔ)路徑(SD卡叫惊,在/storage/emulated/0目錄下)
appDir = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
//獲取內(nèi)部存儲(chǔ)路徑(默認(rèn)在/date/user/0/(packageName)目錄下)
appDir = context.getCacheDir().getAbsolutePath();
}
File appFile = new File(appDir);
if (!appFile.exists()) {
appFile.mkdirs();
}
return appFile;
}
/**
* 【說(shuō)明】:獲取應(yīng)用基礎(chǔ)文件夾(應(yīng)用相關(guān)文件都會(huì)存儲(chǔ)在該目錄下)
*
* @param context 上下文
* @return File 文件夾(.../AppNamexx/)
*/
public static File getBaseDir(Context context) {
File baseFile = new File(getAppDir(context), FileConstant.APP_BASE_DIR_NAME);
if (!baseFile.exists()) {
baseFile.mkdirs();
}
return baseFile;
}
/**
* 【說(shuō)明】:獲取應(yīng)用日志文件夾
*
* @param context 上下文
* @return File 文件夾(.../AppNamexx/Log/)
*/
public static File getLogDir(Context context) {
File logFile = new File(getBaseDir(context), FileConstant.APP_LOG_DIR_NAME);
if (!logFile.exists()) {
logFile.mkdirs();
}
return logFile;
}
/**
* 【說(shuō)明】:獲取應(yīng)用崩潰日志文件夾
*
* @param context 上下文
* @return File 文件夾(.../AppNamexx/Log/Crash/)
*/
public static File getCrashDir(Context context) {
File crashFile = new File(getLogDir(context), FileConstant.APP_LOG_CRASH_DIR_NAME);
if (!crashFile.exists()) {
crashFile.mkdirs();
}
return crashFile;
}
}
CrashHandler.java
public class CrashHandler implements Thread.UncaughtExceptionHandler{
private static final String TAG = "CrashHandler";
/*系統(tǒng)默認(rèn)的UncaughtException處理類*/
private Thread.UncaughtExceptionHandler defaultHandler;
private Context context;
private static CrashHandler instance = new CrashHandler();
/*用來(lái)存儲(chǔ)設(shè)備信息和異常信息*/
private Map<String, String> infos = new HashMap<String, String>();
private CrashHandler() {
}
public static CrashHandler getInstance() {
return instance;
}
public void init(Context context) {
this.context = context;
//獲取系統(tǒng)默認(rèn)的UncaughtException處理器
this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
//設(shè)置該CrashHandler為程序的默認(rèn)處理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 【說(shuō)明】:當(dāng)UncaughtException發(fā)生時(shí)會(huì)轉(zhuǎn)入該方法來(lái)處理
*
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && defaultHandler != null) {
//如果用戶沒(méi)有處理則讓系統(tǒng)默認(rèn)的異常處理器處理
defaultHandler.uncaughtException(thread, ex);
}
}
/**
* 【說(shuō)明】:自定義錯(cuò)誤處理(包括收集錯(cuò)誤信息,生成錯(cuò)誤日志文件)
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
collectDeviceInfo(context);
saveCrashInfo2File(ex);
return true;
}
/**
* 【說(shuō)明】:收集應(yīng)用參數(shù)信息
*/
private void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();//獲取應(yīng)用包管理者對(duì)象
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
String packageName = pi.packageName;
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
infos.put("packageName", packageName);
infos.put("appName", ctx.getString(R.string.app_name));
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "an error occurred when collect package info...", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
} catch (IllegalAccessException e) {
Log.e(TAG, "an error occurred when collect crash info...", e);
}
}
}
/**
* 【說(shuō)明】:保存錯(cuò)誤信息到指定文件中
*/
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sbf = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sbf.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sbf.append(result);
try {
//格式化日期做修,作為文件名的一部分
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = dateFormat.format(new Date());
long timestamp = System.currentTimeMillis();
String fileName = "crash-" + time + "-" + timestamp + ".log";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File dir = FileUtil.getCrashDir(context);
String filePath = dir.getAbsoluteFile() + File.separator + fileName;
FileOutputStream fos = new FileOutputStream(filePath);
Log.e(TAG, "log file path:" + filePath);
fos.write(sbf.toString().getBytes());
fos.close();
}
return fileName;
} catch (FileNotFoundException e) {
Log.e(TAG, "an error occurred while find file...", e);
} catch (IOException e) {
Log.e(TAG, "an error occurred while writing file...", e);
}
return null;
}
}