import android.os.Build;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RealTimeProcess {
private String TAG = "RealTimeProcess";
private ProcessBuilder mProcessBuilder;
private Process recordProcess;
private BufferedReader readStdout;
private BufferedReader readStderr;
private RealtimeProcessListener realtimeProcessListener; // 回调用到的接口
private String tmp1;
private String tmp2;
public RealTimeProcess(RealtimeProcessListener realtimeProcessListener) {
this.realtimeProcessListener = realtimeProcessListener;
}
public void start(String... commands) {
try {
mProcessBuilder = new ProcessBuilder(commands).redirectErrorStream(true);
recordProcess = mProcessBuilder.start();
exec(recordProcess);
} catch (Exception e) {
}
}
private void exec(final Process process) {
readStdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
readStderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
Thread execThread = new Thread() {
public void run() {
try {
while ((tmp1 = readStdout.readLine()) != null || (tmp2 = readStderr.readLine()) != null) {
if (tmp1 != null) {
realtimeProcessListener.onNewStdoutListener(tmp1);
}
if (tmp2 != null) {
realtimeProcessListener.onNewStderrListener(tmp2);
}
}
} catch (IOException e) {
realtimeProcessListener.onProcessFinish();
}
}
};
execThread.start();
}
public void destroyRealtimeProcess() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (recordProcess.isAlive()) {
recordProcess.destroyForcibly();
}
}
}
public interface RealtimeProcessListener {
public void onNewStdoutListener(String tmp1);
public void onNewStderrListener(String tmp2);
public void onProcessFinish();
}
}
使用时可以做到抓取,同时也存在一个问题
因为大部分安卓固件存在一个日志缓冲区限制,当日志过多超出最大限制就不会再打印日志
所以需要在开发者模式找到日志缓冲区大小,调到最大测试
参考文章:
版权声明:本文为Mr_su_9726原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。