我通过NotificationManager发布文件上传进度,但在更新其进度时,用户界面冻结。
我使用NotificationCompat.Builder,它在类字段中缓存。因此,进度发布非常简单:
manager.notify(id, uploader.
setProgress(MAX_PROGRESS, (int) (progress * 100), false).
build()
);
保证更新进度从主线程执行(包装在Handler装饰器中)。
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);
}
那为什么它的工作如此缓慢?
答案 0 :(得分:9)
这是一种常见的行为。您不应该频繁更新NotificationManager。您应该决定更新的时间间隔,例如每秒两次。
例如,
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;
这对我来说非常有效,也不会冻结通知。