问题描述
我通过NotificationManager发布文件上传进度,但是在更新进度时,UI冻结了.
I publish file upload progress via NotificationManager, but while updating its progress UI freezes.
我使用NotificationCompat.Builder,它缓存在class字段中.因此进度发布非常简单:
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()
);
保证更新进度是从主线程(包装在Handler装饰器中)执行的.
Update progress is guaranteed to execute from the main thread(wrapped in Handler decorator).
this.request.setCallback(new UploaderDecorator(this.request.getCallback()));
最新进展如下:
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);
}
那为什么它这么慢?
推荐答案
这是常见的行为.您不应该将频繁的更新充斥到NotificationManager中.您应该确定一个更新间隔,例如每秒两次.
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.
例如,
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.
这篇关于为什么NotificationManager在更新过程中工作如此缓慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!