-1

I am having a code to store the log files to a SD card in android. The following is the code.

process = Runtime.getRuntime().exec("logcat "+ LOG_TAG +":D *:S");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    //do something over here
}

It is running an infinite loop. Any help.

inquisitive
  • 3,738
  • 6
  • 30
  • 56

3 Answers3

1

As logCat never ends, you might try to force an end when InputStream.available() == 0. I did this using wrapping the original InputStream in an ImpatientInputStream.

As at the very first start available might be 0 because of the non-blocking nature, you might add a flag whether something read already.

BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(
            new ImpatientInputStream(process.getInputStream())
        ));


public class ImpatientInputStream extends InputStream {

    private final InputStream in;
    private boolean eof;

    public ImpatientInputStream(InputStream in) {
        this.in = in;
    }

    @Override
    public int read() throws IOException {
        if (eof) {
            return -1; 
        }
        if (available() == 0) {
            eof = true;
            return -1;
        }
        return in.read();
    }

}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

logcat never stops, it waits for the next line to display, so readLine() blocks while waiting for the next input from the process.

You can however redirect the output of the command directly with -f filename as explained here.

This answer has everything you need.

Community
  • 1
  • 1
Djon
  • 2,230
  • 14
  • 19
0

You can provide timestamp/time period in while loop. Below sample will make this more clear

Sample :

        while (System.currentTimeMillis() < end_time) {
        //do your stuffs here

        while ((line = bufferedReader.readLine()) != null) {
       //do something over here
        }
        }
VVB
  • 7,363
  • 7
  • 49
  • 83