Skip to content

Instantly share code, notes, and snippets.

@wangmuy
Last active July 6, 2017 04:13
Show Gist options
  • Save wangmuy/3b853aa3a4fd8df40701e452c47e0b99 to your computer and use it in GitHub Desktop.
Save wangmuy/3b853aa3a4fd8df40701e452c47e0b99 to your computer and use it in GitHub Desktop.
[threaded logcat] Get threaded logcat #logcat #process #InputStream
class ThreadedLogcat {
private boolean mClear;
private String mOutputFile;
private Thread mLoggingThread;
private Process mP;
private void stopLogging() {
if(mLoggingThread == null)
return;
try {
if(mP != null) mP.destroy();
mLoggingThread.join();
mLoggingThread = null;
} catch (InterruptedException e) {
Logger.error("", e);
}
}
private void startLogging() {
// TODO: set uncaught handler to recover from exceptions
final String cmd = (mClear? "logcat -c; ":"") + "logcat -vtime "+mLogTag;//+" -f "+mOutputFile;
try {
mP = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});
} catch (IOException e) {
Logger.error("", e);
}
mLoggingThread = new Thread(new Runnable() {
@Override
public void run() {
InputStreamReader isr = null;
FileWriter fw = null;
try {
char[] buffer = new char[128];
int len;
isr = (new InputStreamReader(mP.getInputStream()));
fw = new FileWriter(mOutputFile);
while((len = isr.read(buffer)) > 0) {
String l = new String(buffer, 0, len);
Logger.debug("[logcat] " + l);
fw.write(buffer, 0, len);
}
fw.flush();
} catch (IOException e) {
Logger.error("", e);
} finally {
if (isr != null) try {
isr.close();
} catch (IOException e) {
Logger.error("", e);
}
if(fw != null) try {
fw.close();
} catch (IOException e) {
Logger.error("", e);
}
}
}
});
mLoggingThread.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment