如何连续读取logcat并写入内部存储文件?

问题描述 投票:4回答:1

连续读取logcat并写入内部存储文件,为此我尝试了以下代码。

public class LogCatTask extends AsyncTask<Void, String, Void> {
    public AtomicBoolean run = new AtomicBoolean(true);

    @Override
    protected Void doInBackground(Void... params) {
        try {

            //create text file in SDCard
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
            dir.mkdirs();
            File file = new File(dir, "logcat.txt");

            Runtime.getRuntime().exec("logcat -c");
            Process process = Runtime.getRuntime().exec("logcat -f "+file);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder log = new StringBuilder();
            String line = "";
            Log.e("log cat task...","while...run.get()."+run.get());
            while (run.get()) {
                line = bufferedReader.readLine();
                //Log.e("log cat task...","while...out.");
                if (line != null) {
                    Log.e("log cat task...","while....");
                    log.append(line);
                    //publishProgress(log.toString());

                    //to write logcat in text file
                    FileOutputStream fOut = new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fOut);

                    // Write the string to the file
                    osw.write(log.toString());
                    osw.flush();
                    osw.close();
                }
                line = null;
                Thread.sleep(10);
                //Log.e("log cat task...","while...out.");
            }
            //Log.e("log cat task...","ouet....while....");
        }
        catch(Exception ex){

        }
        return null;
    }
}

一旦上面的代码运行,它读取logcat和写入存储,但高达一些部分的日志,它只读.它不是读continuos.How to read the logcat continuous?

android logging logcat
1个回答
0
投票

下面是一个工作代码片段

    try {
        Process process = Runtime.getRuntime().exec("logcat");
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

        StringBuilder log=new StringBuilder();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            // do what you want with the line you just read
            // you're in an infinite loop continuously reading the log,
            // you might want to add some mechanism to break out of it
        }
    }
    catch (IOException  e) {
        fail("failed to get log");
    }

你的代码过于复杂,容易出现竞赛条件。 例如,logcat -c是否保证在logcat -f命令之前完成。-f命令将输出重定向到一个文件,而你的逻辑也试图写到同一个文件,这是很有问题的。我注意到logcat的一些选项,比如"-T "在程序上是行不通的。也许"-f "选项也有问题。 如果你只想读取到当前时间的日志文件,请使用 "logcat -d"。

© www.soinside.com 2019 - 2024. All rights reserved.