gpt4 book ai didi

java - 如何指定在循环内 x 秒后调用 publishProgress()?

转载 作者:搜寻专家 更新时间:2023-11-01 08:00:32 24 4
gpt4 key购买 nike

由于垃圾收集器被调用了很多次,我一直在寻找一种在循环语句中 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 循环中实现它。

最佳答案

这个解决方案不会阻塞 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();

关于java - 如何指定在循环内 x 秒后调用 publishProgress()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21881613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com