5

我需要以某种方式监视 LogCat 日志,这意味着在我的服务运行时,我需要读取 LogCat 以获取新条目。目前我只知道如何检索一次日志:

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 选项,它不会退出,但也不会工作。那么如何修改波纹管代码以不断地从 LogCat 读取新条目?

4

2 回答 2

6

我就是这样做的,使用刘嘉豪的建议:

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;
    }
  }
}
于 2012-08-09T04:51:06.473 回答
2

您可以创建一个新线程以在后台运行 logcat(不带选项 -d)。

注意:使用缓冲事件代替进程ActivityManager,更准确。“logcat -b 事件”

于 2011-05-01T19:32:12.330 回答