以下是如何读取当前应用程序的日志.要过滤日志,我获取进程ID(pid)并将其与logcat输出的每一行进行比较.
在logcat的参数中,我指定读取最后200行并随时间显示日志.
public String writeLogToFile() {
StringBuilder logs = new StringBuilder();
int pid = android.os.Process.myPid();
String pidPattern = String.format("%d):",pid);
try {
Process process = new ProcessBuilder()
.command("logcat","-t","200","-v","time")
.redirectErrorStream(true)
.start();
InputStream in = null;
try {
in = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(pidPattern)) {
logs.append(line).append("\n");
}
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e(TAG,"Cannot close input stream",e);
}
}
}
} catch (IOException e) {
Log.e(TAG,"Cannot read logs",e);
}
return log.toString();
}