2012-04-16 46 views
2

我看到有人抱怨Logcat只輸出最後一行。我想問一個保留的問題,我該如何產生這種只輸出最後一行的條件?如何才能只讀最後一行的logcat?

這是我如何通過啓動線程來讀取日誌。

public class ReadLog implements Runnable{ 
     private boolean running = true; 

     public void stop(){ 
      running = false; 
     } 

     @Override 
     public void run() { 
      Process proc = null; 
      try { 
       //Runtime.getRuntime().exec("/system/bin/logcat -c"); 
       proc = Runtime.getRuntime().exec("/system/bin/logcat "); 
       }catch(IOException e) { 
        e.printStackTrace(); 
      } 
      if(proc != null){ 
       BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); 
       String line= null; 
       try { 
        while((line=reader.readLine())!=null && running){ 
         if(line.contains("specific word")){ 
          doSomething();//do something base on log 
          running = false; 
         } 
        } 
       } 
       catch (IOException e) { 
        e.printStackTrace(); 
       } 
       finally{ 
        proc.destroy(); 
       } 
      } 
     } 
    } 

我只想讀最新的一行。問題是它會觸發doSomething(),即使「特定字」不在最後一行,除非在開始運行之前添加Runtime.getRuntime().exec("/system/bin/logcat -c");行來清除日誌。

確實,我可以再添加一個while((line=reader.readLine())!=null && running){}讓BufferedReader在開始運行之前進入最後一行,但可能需要很長時間和太晚。

我試過Runtime.getRuntime().exec("/system/bin/logcat | tail -n 1"); 但沒有運氣,tail不接受標準輸入。 我要求任何命令輸出stdout的最後一行,就像tail -n 1 FILE一樣。

回答

0

嘗試Runtime.getRuntime().exec("/system/bin/logcat -d | tail -n 1");

根據logcat的文檔 - > -d: 「轉儲日誌到屏幕並退出。」

然後readline將返回最後一個新行。 (我沒有測試它)。

編輯:

事實上| tail -n 1有沒有效果「執行」,但與「-d」你可以很容易地獲得最後的日誌行。

try { 
    //Executes the command. 
    Process process = Runtime.getRuntime().exec(
     "/system/bin/logcat -d"); 

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

    String output; 
    String lastLine = null; 
    while ((output = reader.readLine()) != null) { 
     lastLine = output; 
    } 
    reader.close(); 

    //Waits for the command to finish. 
    process.waitFor(); 

    if(lastLine != null) 
     System.out.println("Last log line : " + lastLine); 
} catch (IOException e) { 
    throw new RuntimeException(e); 
} catch (InterruptedException e) { 
    throw new RuntimeException(e); 
} 

不要忘記READ_LOGS允許添加到您的清單

<uses-permission android:name="android.permission.READ_LOGS" /> 
+0

我試過了。沒有-d,沒有什麼不同。唯一不同的是該過程將退出或不退出。 – Yeung 2012-05-24 05:05:16

+0

我的第一個解決方案不工作,但我做了一個新的解決方案,它適用於我在Android 2.3.3上,我希望這可以解決您的問題,對不起,我沒有看到你已經測試了這一點,我無法幫助你,這是我找到的唯一途徑 – Duffydake 2012-05-26 14:41:16

相關問題