如何constanly监视LogCat中的文件?文件、constanly、LogCat

2023-09-05 11:27:53 作者:执酒笑白衣

我需要以某种方式监视LogCat中的日志,这意味着,虽然我的服务正在运行我需要阅读的LogCat中的新条目。 在这一刻,我只知道如何找回曾经的日志:

I need to somehow monitor the LogCat log, meaning that while my service is running I need to read the LogCat for new entries. At this moment I know only how to retrieve once the Log:

Process mLogcatProc = null;
    BufferedReader reader = null;
    try
    {
            mLogcatProc = Runtime.getRuntime().exec(new String[]
                   {"logcat", "-d", "ActivityManager:I *:S" });        

            reader = new BufferedReader(new InputStreamReader
    (mLogcatProc.getInputStream()));

            String line;
            final StringBuilder log = new StringBuilder();
            String separator = System.getProperty("line.separator"); 

            while ((line = reader.readLine()) != null)
            {
                    log.append(line);
                    log.append(separator);
            }

如果我删除了-d选项也不会退出,而且它也不会有的工作。 所以,我怎么可以修改波纹管code,才能不断从LogCat中读出新的作品?

If I remove the -d option it will not exit but also it will not either work. So how can I modify the bellow code in order to continuously read new entries from LogCat?

推荐答案

这是我做到了,用嘉浩刘的建议:

This is how I did it, using Jiahao Liu's suggestion:

ReadThread thread;

public void startRecordingLogs()
{
  if(thread == null || !thread.isAlive())
  {
    ReadThread thread = new ReadThread();
    thread.start();
  }
}

public String stopRecordingLogs()
{
  String results = thread.stopLogging();
  return results;
}

private class ReadThread extends Thread{

  String results;
  Process process;
  Object lockObject = new Object();

  public void run(){
    synchronized(lockObject)
    {
      process = Runtime.getRuntime().exec("logcat -v time");        

      reader = new BufferedReader(new InputStreamReader (process.getInputStream()));

      String line;
      final StringBuilder log = new StringBuilder();
      String separator = System.getProperty("line.separator"); 

      while ((line = reader.readLine()) != null)
      {
        log.append(line);
        log.append(separator);
      }
    }

    results = log.toString();
  }

  public String stopLogging()
  {
    process.destroy();
    synchronized(lockObject)
    {
      return results;
    }
  }
}