Reputation: 191
I was looking for a way to call publishProgress() after x seconds in a loop statement due to Garbage Collector being called a lot of times.
This is what I have:
protected Void doInBackground(Void... parms) {
Long size = source.length();
InputStream input = new FileInputStream(source);
OutputStream output = new FileOutputStream(destination);
// Transfer bytes from input to output
byte[] buf = new byte[1024];
int len;
long written = 0;
while ((len = input.read(buf)) > 0)
{
output.write(buf, 0, len);
written += 1024;
//This should be called after x seconds
publishProgress((int) (written * 100 / size));
}
input.close();
output.close();
}
I have found ScheduledExecutorService
but I don't know how to implement it inside while loop.
Upvotes: 2
Views: 125
Reputation: 664
This solution will not block UI thread, As it use AsyncTask
Long size = source.length();
InputStream input = new FileInputStream(source);
OutputStream output = new FileOutputStream(destination);
// Transfer bytes from input to output
byte[] buf = new byte[1024];
int len;
long written = 0;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
written += 1024;
Long size = source.length();
InputStream input = new FileInputStream(source);
OutputStream output = new FileOutputStream(destination);
// Transfer bytes from input to output
byte[] buf = new byte[1024];
int len;
long written = 0;
while ((len = input.read(buf)) > 0) {
output.write(buf, 0, len);
written += 1024;
(new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... parms) {
mEventDataSource.deleteAll();
try {
Thread.currentThread().sleep(x * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// This should be called after x seconds
publishProgress((int) (written * 100 / size));
}
}).execute();
}
input.close();
output.close();
Upvotes: 2
Reputation: 348
You can use CountdownTimer class as follows,
while ((len = input.read(buf)) > 0)
{
output.write(buf, 0, len);
written += 1024;
// will call publicshProgress after 30 seconds.
new CountDownTimer(30000, 1000)
{
public void onTick(long millisUntilFinished) {}
public void onFinish()
{
//This should be called after x seconds
publishProgress((int) (written * 100 / size));
}
}.start();
}
Upvotes: 0
Reputation: 2005
put this line inside loop
handler.postDelayed(runnable, x);
and this in your activity
Runnable runnable = new Runnable() {
@Override
public void run() {
publishProgress((int) (written * 100 / size));
}
};
Handler handler = new Handler();
Upvotes: 2