How to programmatically read logcat in real time?

隐身守侯 提交于 2019-12-11 04:45:38

问题


I have a service that would like to read data from logcat, from the start of the service (i.e. discarding logcat data prior to service start), monitoring the logcat data in real time, filtering the logcat to only show tags of "ActivityManager" and informational logs.

I would then like to perform certain actions based on the filtered logcat data. I tried the following, but it doesn't work:

Runtime.getRuntime().exec("logcat -c"); // flush the logcat first
Process process = Runtime.getRuntime().exec("logcat ActivityManager:I"); // filters logcat to only "ActivityManager:I" logs
BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(process.getInputStream()));

StringBuilder log = new StringBuilder();
String line = "";
Log.d(TAG,  "Reading filtered logcat");
while ((line = bufferedReader.readLine()) != null) {
    log.append(line);
}

Does anyone know where I'm going wrong?


回答1:


OK, turns out I missed out the -s parameter in logcat, which filters the logcat output.




回答2:


I'd recommend taking a look at the question and answers posted in this SO post. I'm not on the machine that I have studio installed on so I can't try this out right now. To help us answer your question, could you give some more information on the problem you are having? When you say that the approach that you have "doesn't work" what do you mean? Does the value of 'log' not change? Is an exception thrown? Are the logs given, but unfiltered?

Also, what you are trying to do may not work on an unrooted device. As this SO post/answer explains you no longer have access to the logs of other applications, only to those of your own application. This means that your service can only read the logs of the application that it is a part of on an unrooted device.



来源:https://stackoverflow.com/questions/38089775/how-to-programmatically-read-logcat-in-real-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!