Victor Laerte
Victor Laerte

Reputation: 6556

What is the best way to publish progress with interval? (Talking about performance)

I have an app that makes a download and unzip of some files and I'm publishing my progress every second using System.currentTimeMillis() to compare the time elapsed.

My issue is that the code seems to make too much work for each byte written or archive unziped, getting the current time and comparing with the started time, to show it or not. My question is there's a better way to make it without lose performance??

My code to compare time elapsed in download:

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;
    }

}

My code to compare time elapsed in unzip:

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

Upvotes: 0

Views: 209

Answers (1)

Gaurav Arora
Gaurav Arora

Reputation: 17274

Use Timer API. Timer allows to execute particular set of code repeatedly after specified amount of time. Might be suitable in your case.

Refer Android Documentation

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);

Upvotes: 1

Related Questions