2011-01-11 79 views
5

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

如果我删除-d选项也不会退出,而且它不会工作。 那么,如何修改波纹管代码以连续读取LogCat中的新条目?

+2

请问你为什么要这么做?这听起来像是一个普遍不好的主意。 – torkildr 2011-01-11 18:42:19

+1

adb logcat?你为什么要在你的程序中使用logcat? – 2011-01-11 18:50:43

回答

2

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

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

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; 
    } 
    } 
}