logcat进程InputStream无法读取Android应用程序中的新日志

时间:2013-07-16 09:58:07

标签: android logcat

我想使用这个类在我的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();
    }
}

1 个答案:

答案 0 :(得分:0)

同样的原因,无法读取其他preccess的logcat。

How can I get logcat on my device to show logs from all processes