如何constanly监视LogCat中的文件? [英] How to constanly monitor LogCat file?

查看:232
本文介绍了如何constanly监视LogCat中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以某种方式监视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;
    }
  }
}

这篇关于如何constanly监视LogCat中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆