如何持续监控LogCat文件?

Ale*_*lex 5 logging monitoring android continuous logcat

我需要以某种方式监视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);
            }
Run Code Online (Sandbox Code Playgroud)

如果我删除-d选项它将不会退出但它也不会工作.那么如何修改波纹管代码以便从LogCat连续读取新条目?

you*_*786 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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 2

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

注意:使用缓冲事件而不是流程ActivityManager,更准确。“logcat -b 事件”