在应用程序中以编程方式读取logcat

我想阅读并对我的应用程序中的logcat日志做出反应。

我发现了下面的代码:

try { Process process = Runtime.getRuntime().exec("logcat -d"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); StringBuilder log=new StringBuilder(); String line = ""; while ((line = bufferedReader.readLine()) != null) { log.append(line); } TextView tv = (TextView)findViewById(R.id.textView1); tv.setText(log.toString()); } catch (IOException e) {} 

这段代码确实返回了在应用程序启动之前所做的logcat日志 –

但是,是否有可能连续听新的logcat日志?

您可以继续阅读日志,只需在上面的代码中删除“-d”标志即可。

“-d”标志指示logcat显示日志内容并退出。 如果您删除该标志,logcat将不会终止,并且不断发送添加到其中的任何新行。

请记住,如果devise不正确,这可能会阻止您的应用程序。

祝你好运。

你可以清除你的logcat用这个方法我用logcat写入文件后清除,以避免重复的行:

 public void clearLog(){ try { Process process = new ProcessBuilder() .command("logcat", "-c") .redirectErrorStream(true) .start(); } catch (IOException e) { } } 

“-c”标志清除缓冲区。

-c清除(刷新)整个日志并退出。

这里有一个快速拼装/插件,可用于捕获所有当前或全部新(自上次请求以来)日志项目。

您应该修改/扩展它,因为您可能想要返回一个连续stream而不是LogCapture。

Android LogCat“手动”: https : //developer.android.com/studio/command-line/logcat.html

 import android.util.Log; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * Created by triston on 6/30/17. */ public class Logger { public static String lineEnding = "\n"; private final String logKey; private static List<String> logKeys = new ArrayList<String>(); Logger(String tag) { logKey = tag; if (! logKeys.contains(tag)) logKeys.add(logKey); } public static class LogCapture { private String lastLogTime = null; public final String buffer; public final List<String> log, keys; LogCapture(String oLogBuffer, List<String>oLogKeys) { this.buffer = oLogBuffer; this.keys = oLogKeys; this.log = new ArrayList<>(); } private void close() { if (isEmpty()) return; String[] out = log.get(log.size() - 1).split(" "); lastLogTime = (out[0]+" "+out[1]); } private boolean isEmpty() { return log.size() == 0; } public LogCapture getNextCapture() { LogCapture capture = getLogCat(buffer, lastLogTime, keys); if (capture == null || capture.isEmpty()) return null; return capture; } public String toString() { StringBuilder output = new StringBuilder(); for (String data : log) { output.append(data+lineEnding); } return output.toString(); } } /** * Get a list of the known log keys * @return copy only */ public static List<String> getLogKeys() { return logKeys.subList(0, logKeys.size() - 1); } /** * Platform: Android * Get the logcat output in time format from a buffer for this set of static logKeys. * @param oLogBuffer logcat buffer ring * @return A log capture which can be used to make further captures. */ public static LogCapture getLogCat(String oLogBuffer) { return getLogCat(oLogBuffer, null, getLogKeys()); } /** * Platform: Android * Get the logcat output in time format from a buffer for a set of log-keys; since a specified time. * @param oLogBuffer logcat buffer ring * @param oLogTime time at which to start capturing log data, or null for all data * @param oLogKeys logcat tags to capture * @return A log capture; which can be used to make further captures. */ public static LogCapture getLogCat(String oLogBuffer, String oLogTime, List<String> oLogKeys) { try { List<String>sCommand = new ArrayList<String>(); sCommand.add("logcat"); sCommand.add("-b"+oLogBuffer); sCommand.add("-vtime"); if (oLogTime != null) { // dump-from-date-to-now sCommand.add("-t"); sCommand.add(oLogTime); } else { // dump-to-now and exit sCommand.add("-d"); } for (String item : oLogKeys) { // for each key/tag select sCommand.add(item+":I"); // log level "info" and higher } sCommand.add("*:S"); // ignore logs which are not selected Process process = new ProcessBuilder().command(sCommand).start(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); LogCapture mLogCapture = new LogCapture(oLogBuffer, oLogKeys); String line = ""; while ((line = bufferedReader.readLine()) != null) { mLogCapture.log.add(line); } mLogCapture.close(); return mLogCapture; } catch (Exception e) { // since this is a log reader, there is nowhere to go and nothing useful to do return null; } } /** * "Error" * @param e */ public void failure(Exception e) { Log.e(logKey, Log.getStackTraceString(e)); } /** * "Error" * @param message * @param e */ public void failure(String message, Exception e) { Log.e(logKey, message, e); } public void warning(String message) { Log.w(logKey, message); } public void warning(String message, Exception e) { Log.w(logKey, message, e); } /** * "Information" * @param message */ public void message(String message) { Log.i(logKey, message); } /** * "Debug" * @param message a Message */ public void examination(String message) { Log.d(logKey, message); } /** * "Debug" * @param message a Message * @param e An failure */ public void examination(String message, Exception e) { Log.d(logKey, message, e); } } 

在执行活动logging的项目中:

 Logger log = new Logger("SuperLog"); // perform logging methods 

当您想要捕捉您通过“logging器”login的所有内容时

 LogCapture capture = Logger.getLogCat("main"); 

当你饿了,你想吃更多的原木

 LogCapture nextCapture = capture.getNextCapture(); 

你可以用一个string获取捕获

 String captureString = capture.toString(); 

或者您可以获取捕获的日志项

 String logItem = capture.log.get(itemNumber); 

没有确切的静态方法来捕获外部日志密钥,但有一种办法

 LogCapture foreignCapture = Logger.getLogCat("main", null, foreignCaptureKeyList); 

使用上面的也将允许你在外部捕获中调用Logger.this.nextCapture

  //CLEAR LOGS Runtime.getRuntime().exec("logcat -c"); //LISTEN TO NEW LOGS Process pq=Runtime.getRuntime().exec("logcat v main"); BufferedReader brq = new BufferedReader(new InputStreamReader(pq.getInputStream())); String sq=""; while ((sq = brq.readLine()) != null) { //CHECK YOUR MSG HERE if(sq.contains("send MMS with param")) { } } 

我在我的应用程序中使用它,它的工作原理。 你可以在Timer Task中使用上面的代码,这样它就不会停止你的主线程

  Timer t; this.t.schedule(new TimerTask() { public void run() { try { ReadMessageResponse.this.startRecord();//ABOVE METHOD HERE } catch (IOException ex) { //NEED TO CHECK SOME VARIABLE TO STOP MONITORING LOGS System.err.println("Record Stopped"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { ReadMessageResponse.this.t.cancel(); } } }, 0L); }