package com.mxn.helper.screenshot.logcat;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LogcatReader implements Runnable {
    private static final String TAG = "LogcatReader";
    private boolean running;
    private LogcatListener listener;

    public LogcatReader(LogcatListener listener) {
        running = true;
        this.listener = listener;
    }

    @Override
    public void run() {
        Process process = null;
        BufferedReader reader = null;

        try {
            // 运行 "logcat" 命令
            process = Runtime.getRuntime().exec("logcat");
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while (running && (line = reader.readLine()) != null) {
                // 处理日志行
                listener.logcat(line);
            }
        } catch (IOException e) {
            listener.logcat("e "+e.getMessage());
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void stop() {
        running = false;
    }

    public interface LogcatListener {
        void logcat(String msg);
    }
}
