I want to read and react to logcat logs within my application.
I found the following code:
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) {}
This code indeed returns the logcat logs that made until the application was started -
But is it possible to continuously listen to even new logcat logs?
The "-c" flag clears the buffer.
-c Clears (flushes) the entire log and exits.
Here is a quick put-together/drop-in that can be used for capturing all current, or all new (since a last request) log items.
You should modify/extend this, because you might want to return a continuous-stream rather than a LogCapture.
The Android LogCat "Manual": https://developer.android.com/studio/command-line/logcat.html import android.util.Log;
In your project which performs activity logging:
When you want to capture everything you logged through "Logger"
When you get hungry and you want to snack on more logs
You can get the capture as a string with
Or you can get the log items of the capture with
There is no exact static method to capture foreign log keys but there is a way none the less
Using the above will also permit you to call
Logger.this.nextCapture
on the foreign capture.You can keep reading the logs, just by removing the "-d" flag in your code above.
The "-d" flag instruct to logcat to show log content and exit. If you remove the flag, logcat will not terminate and keeps sending any new line added to it.
Just have in mind that this may block your application if not correctly designed.
good luck.
You can clear your logcat with this method i'm using to clear after writing logcat to a file to avoid duplicated lines:
I am using this in my app and it works . And you can use above code in Timer Task so that it wont stop your main thread