2

我看到有人抱怨 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.

4

1 回答 1

1

尝试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);
}

不要忘记在清单中添加 READ_LOGS 权限

<uses-permission android:name="android.permission.READ_LOGS" />
于 2012-05-11T01:29:31.887 回答