我看到有人提示 Logcat 只输出最后一行。我想问一个保留问题,我怎样才能产生这种只输出最后一行的条件?
这就是我通过启动线程读取日志的方式。
public class ReadLog implements Runnable{
private boolean running = true;
public void stop(){
running = false;
}
@Override
public void run() {
Process proc = null;
try {
//Runtime.getRuntime().exec("/system/bin/logcat -c");
proc = Runtime.getRuntime().exec("/system/bin/logcat ");
}catch(IOException e) {
e.printStackTrace();
}
if(proc != null){
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line= null;
try {
while((line=reader.readLine())!=null && running){
if(line.contains("specific word")){
doSomething();//do something base on log
running = false;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally{
proc.destroy();
}
}
}
}
我只想阅读最新的一行。问题是它会触发 doSomething() 即使“特定词”不在最后一行,除非我添加 Runtime.getRuntime().exec("/system/bin/logcat -c");
在开始运行之前清除日志的行。
的确,我可以再添加一个 while((line=reader.readLine())!=null && running){}
让 BufferedReader 在开始运行之前转到最后一行但是这可能需要很长时间而且为时已晚。
我试过 Runtime.getRuntime().exec("/system/bin/logcat | tail -n 1");
但不幸的是 tail
不接受标准输入。
我要求任何像 tail -n 1 FILE
一样快速输出最后一行 stdout 的命令。
最佳答案
尝试 Runtime.getRuntime().exec("/system/bin/logcat -d | tail -n 1");
根据 logcat 文档 -> -d:“将日志转储到屏幕并退出。”
然后 readline 将返回最后一个新行。 (我没有测试)。
编辑:
事实上| tail -n 1
对“exec”没有影响,但使用“-d”可以轻松获取最后一行日志。
try {
//Executes the command.
Process process = Runtime.getRuntime().exec(
"/system/bin/logcat -d");
BufferedReader reader = new BufferedReader(
new InputStreamReader(process
.getInputStream()));
String output;
String lastLine = null;
while ((output = reader.readLine()) != null) {
lastLine = output;
}
reader.close();
//Waits for the command to finish.
process.waitFor();
if(lastLine != null)
System.out.println("Last log line : " + lastLine);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
不要忘记为您的 list 添加 READ_LOGS 权限:
<uses-permission android:name="android.permission.READ_LOGS" />
关于android - 如何只读取最后一行的 logcat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10170884/