[英]How can I specify publishProgress() to be called after x seconds inside a loop?
我一直在寻找一种在循环语句中经过x秒后调用publishProgress()的方法,因为垃圾回收器被多次调用了。
这就是我所拥有的:
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();
}
我找到了ScheduledExecutorService
但是我不知道如何在while循环中实现它。
将此行放入循环
handler.postDelayed(runnable, x);
这在你的活动中
Runnable runnable = new Runnable() {
@Override
public void run() {
publishProgress((int) (written * 100 / size));
}
};
Handler handler = new Handler();
此解决方案不会阻塞UI线程,因为它使用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();
您可以按以下方式使用CountdownTimer类,
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.