bvi*_*iyg 5 android android-notifications
我通过NotificationManager发布文件上传进度,但在更新其进度时,用户界面冻结.
我使用NotificationCompat.Builder,它在类字段中缓存.因此,进度发布非常简单:
manager.notify(id, uploader.
setProgress(MAX_PROGRESS, (int) (progress * 100), false).
build()
);
Run Code Online (Sandbox Code Playgroud)
保证更新进度从主线程执行(包装在Handler装饰器中).
this.request.setCallback(new UploaderDecorator(this.request.getCallback()));
Run Code Online (Sandbox Code Playgroud)
进展情况如下:
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);
}
Run Code Online (Sandbox Code Playgroud)
那为什么它的工作如此之慢?
这是一种常见的行为.您不应该频繁更新泛洪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;
Run Code Online (Sandbox Code Playgroud)
这对我来说非常合适,也不会冻结通知.
| 归档时间: |
|
| 查看次数: |
1618 次 |
| 最近记录: |