到目前为止,我已经找到了一种获取 logcat 的方法,并且正在为此解决……现在
在主Activity onCreate 调用这个方法;
public static void saveLogcatToFile(Context context) {
File outputFile = new File(context.getFilesDir(), "logcat.txt");
try {
@SuppressWarnings("unused")
Process process = Runtime.getRuntime().exec("logcat -df " + outputFile.getAbsolutePath());
} catch (IOException e) {...
在另一个 Activity 的 onCreate 中,使用 logcat 填充 TextView;
public static String readLogcatFromFile(Context context) {
File logFile = new File(context.getFilesDir(), "logcat.txt");
if (logFile.exists() == false) { ...
String logContents = context.getString(R.string.EMPTY_STRING);
FileInputStream fileInStream = null;
try {
fileInStream = new FileInputStream(logFile);
logContents = convertStreamToString(fileInStream);
} catch (Exception e) { ...
} finally { ...
fileInStream.close();
}
return logContents;
}
private static String convertStreamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
每次运行的日志都会不断追加,直到您卸载(这会删除日志文件)。当我破坏某些东西并且我的应用程序在启动时死机时,我发现它特别有用,因为我可以恢复到先前的提交并查看日志以查看发生了什么