Ben Siver
Ben Siver

Reputation: 2948

Android: AsyncTask and continuous file IO

I'm attempting to use an AsyncTask to read from a file at regular intervals. The file has a hard-coded "EOL" type separator between each interval of lines I want to read. My current implementation involves an AsyncTask reading the first interval of lines using a BufferedReader until it approaches the EOL marker, then does some updating of the UI with publishProgress(), waits a period of time, and should then move on to the next interval of text.

My question is the following: how can I accomplish moving on to the next interval of text while using an AsyncTask? It seems like I have to keep calling new() on the BufferedReader for each interval, which in turn resets my position in the file. Are there any alternate libraries I can use? Note that I need to keep the AsyncTask, as I am attempting to simulate the data being streamed in from a live source every X seconds.

I can provide some code if necessary, but this is mainly a high-level design question.

Upvotes: 0

Views: 720

Answers (3)

Gallal
Gallal

Reputation: 4262

Have a loop in your doInBackground implementation of AsynTask and then at the end of each loop (when your reach EOL) call a Activity.runOnUiThread(Runnable) to update the UI. This way you never leave do in background and you don't have to lose your reference to your position.

Another option is to use a Handler.

Upvotes: 1

Dan S
Dan S

Reputation: 9189

The AsyncTask is oriented towards completing a "whole" task but not "partial" tasks. Although it is possible to force it to do things this way it may not be as easy. I would suggest using a slightly different design in order to use the AsyncTask more effectively. Keep your BufferedReader as part of your file's state and pass it to the AsyncTask to compute only the difference between the last read and the next read.

Upvotes: 1

Moog
Moog

Reputation: 10193

Keep a long variable that holds your byte count and use the skip(long bytecount) method.

Alternatively subclass AsyncTask and give it a static BufferedReader as a member field

Upvotes: 1

Related Questions