如何在Android中读取系统日志文件?

时间:2010-07-22 17:37:19

标签: android

我正在尝试在我的代码中读取系统日志以生成类似错误报告的内容。 与adb logcat类似,但采用编程方式。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:6)

Log Collector在Google Code上提供了源代码。他们实际上只是调用logcat。见这里:android-log-collector - SendLogActivity.java

以下是关键部分:

ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat");//$NON-NLS-1$
commandLine.add("-d");//$NON-NLS-1$
ArrayList<String> arguments = ((params != null) && (params.length > 0)) ? params[0] : null;

if (null != arguments){
    commandLine.addAll(arguments);
}

Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;
while ((line = bufferedReader.readLine()) != null){ 
     log.append(line);
     log.append(App.LINE_SEPARATOR); 
}

答案 1 :(得分:0)

您可以使用内置错误报告系统。有关我博客的更多信息,请访问:http://blog.tomtasche.at/2012/10/use-built-in-feedback-mechanism-on.html

ApplicationErrorReport report = new ApplicationErrorReport();
report.packageName = report.processName = getApplication()
    .getPackageName();
report.time = System.currentTimeMillis();
report.type = ApplicationErrorReport.TYPE_CRASH;
report.systemApp = false;

ApplicationErrorReport.CrashInfo crash = new ApplicationErrorReport.CrashInfo();
crash.exceptionClassName = e.getClass().getSimpleName();
crash.exceptionMessage = e.getMessage();

StringWriter writer = new StringWriter();
PrintWriter printer = new PrintWriter(writer);
e.printStackTrace(printer);

crash.stackTrace = writer.toString();

StackTraceElement stack = e.getStackTrace()[0];
crash.throwClassName = stack.getClassName();
crash.throwFileName = stack.getFileName();
crash.throwLineNumber = stack.getLineNumber();
crash.throwMethodName = stack.getMethodName();

report.crashInfo = crash;

Intent intent = new Intent(Intent.ACTION_APP_ERROR);
intent.putExtra(Intent.EXTRA_BUG_REPORT, report);
startActivity(intent);