Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
849 views
in Technique[技术] by (71.8m points)

android - Why NotificationManager works so slow during the update progress?

I publish file upload progress via NotificationManager, but while updating its progress UI freezes.

I use NotificationCompat.Builder, which cached in the class field. So progress publishing is a very simple:

manager.notify(id, uploader.
    setProgress(MAX_PROGRESS, (int) (progress * 100), false).
    build()
);

Update progress is guaranteed to execute from the main thread(wrapped in Handler decorator).

this.request.setCallback(new UploaderDecorator(this.request.getCallback()));

The very publication of progress is as follows:

long total = file.length();
long uploaded = 0;
int bytesRead = input.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
    output.write(buffer, 0, bufferSize);
    uploaded += bytesRead;
    callback.onUploadProgress(activeFile, ((float) uploaded / total));
    bytesRead = input.read(buffer, 0, bufferSize);
}

So why it's works so slow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a common behavior. You shouldn't flood the NotificationManager with frequent updates. You should decide an interval to update, like twice every second.

For example,

long startTime;
long elapsedTime = 0L;

if (elapsedTime > 500) {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            mBuilder.setProgress(100, (int) newValue, false);
            mNotifyManager.notify(notificationID, mBuilder.build());

            startTime = System.currentTimeMillis();
            elapsedTime = 0;
        }
    });

    Log.d("Andrognito", newValue + "Progress");
}
else
    elapsedTime = new Date().getTime() - startTime;

This works perfectly for me and doesn't freeze the notifications too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...