Java 按时间间隔发布进度的最佳方式是什么?(谈论性能)
我有一个可以下载和解压一些文件的应用程序,我正在使用System.currentTimeMillis()每秒发布我的进度,以比较经过的时间 我的问题是,代码似乎对写入的每个字节或未压缩的每个字节都做了太多的工作,获取当前时间并与开始时间进行比较,以显示它或不显示它。我的问题是,有没有更好的方法,使它不失去性能 比较下载过程中所用时间的代码:Java 按时间间隔发布进度的最佳方式是什么?(谈论性能),java,android,performance,Java,Android,Performance,我有一个可以下载和解压一些文件的应用程序,我正在使用System.currentTimeMillis()每秒发布我的进度,以比较经过的时间 我的问题是,代码似乎对写入的每个字节或未压缩的每个字节都做了太多的工作,获取当前时间并与开始时间进行比较,以显示它或不显示它。我的问题是,有没有更好的方法,使它不失去性能 比较下载过程中所用时间的代码: protected void afterWrite(int n) throws IOException { super.afterWrite(n);
protected void afterWrite(int n) throws IOException {
super.afterWrite(n);
if (DownloadAndUnzipService.canceled) {
throw new IOException();
}
if (MainViewActivity.isPaused) {
throw new IOException();
}
bytesWritten += n;
showTime = System.currentTimeMillis();
if (showTime - startTime > 1000) {
Bundle resultData = new Bundle();
resultData.putLong("bytesWritten", bytesWritten);
resultData.putString("typeDownload", typeDownload);
resultData.putInt("imageIndex", index);
receiver.send(Constants.UPDATE_PROGRESS, resultData);
startTime = showTime;
}
}
比较解压过程中经过的时间的我的代码:
...
if (showTime - startTime > 1000) {
Bundle resultData = new Bundle();
resultData.putInt("progress", (int) (filesWritten * 100 / fileLength));
resultData.putInt("imageIndex", i);
resultData.putString("typeDownload", typeDownload);
receiver.send(Constants.UPDATE_ZIP_PROGRESS, resultData);
startTime = showTime;
}
ze = zis.getNextEntry();
}
使用
Timer
API。计时器允许在指定的时间后重复执行特定的代码集。可能适合你的情况
提及
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);