0

我有一个应用程序可以下载和解压缩一些文件,并且我每秒都会使用 System.currentTimeMillis() 发布我的进度来比较经过的时间。

我的问题是代码似乎为每个写入的字节或解压缩的存档做了太多工作,获取当前时间并与开始时间进行比较,以显示与否。我的问题是有没有更好的方法可以在不损失性能的情况下做到这一点?

我比较下载时间的代码:

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();
                    }
4

1 回答 1

1

使用TimerAPI。计时器允许在指定的时间后重复执行特定的代码集。可能适合您的情况。

参考安卓文档

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);
于 2013-04-23T17:48:18.807 回答