我想在我的android应用程序中使用这个类来读取logcat,在一段时间内开始和停止。在我调用 start() 之后,它可以工作,并且一些日志已添加到 StringBuilder。但是在我等待一段时间以确保新的 logcat 出现之后,InputStream 阅读器无法读取新字节。当我调用 stop() 时,StringBuilder 没有预期的太多日志。
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LogcatUtils {
public static StringBuilder logcatSB;
public static Thread thread;
public static Process process;
public static void start() {
try {
Runtime.getRuntime().exec("logcat -c");
logcatSB = new StringBuilder();
thread = new Thread(new Runnable() {
@Override
public void run() {
try {
process = Runtime.getRuntime().exec("logcat");
InputStream inputStream = process.getInputStream();
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[32];
try {
while (true) {
int read = inputStream
.read(buffer, 0, 32);
if (read == -1) {
break;
}
bo.write(buffer, 0, read);
bo.flush();
logcatSB.append(bo.toString());
}
} finally {
bo.close();
}
} finally {
inputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "logcatThread");
thread.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void addPidFilter(long pid) {
}
public static void stop() {
process.destroy();
thread.interrupt();
thread = null;
}
public static String getLog() {
return logcatSB.toString();
}
}