android - 如何仅以 10% 的增量调用 NotificationManager
问题描述
我有一个上传照片的服务正在运行。我有一个由 NotificationManager 更新的进度条,但是它被多次调用。
IntentService[n identical 127 lines
我怎样才能让经理只在上传 10% 的增量时通知?
@Override
public void writeTo(@NonNull BufferedSink sink) throws IOException {
long fileLength = mFile.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream in = new FileInputStream(mFile);
long uploaded = 0;
int read;
while (is_uploading && (read = in.read(buffer)) != -1) {
int percent = 10* (int) (10 * uploaded / fileLength);
mManager.notify(NOTIFICATION_ID, uploadingProgressNotification(String.valueOf(current_image_uploading+1), percent + 10));
uploaded += read;
sink.write(buffer, 0, read);
}
}
编辑:
@Override
public void writeTo(@NonNull BufferedSink sink) throws IOException {
long fileLength = mFile.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream in = new FileInputStream(mFile);
long uploaded = 0;
int read;
while (is_uploading && (read = in.read(buffer)) != -1) {
int percent = 10* (int) (10 * uploaded / fileLength);
if(percent % 10 == 0){
Log.d(TAG, "writeTo: test");
mManager.notify(NOTIFICATION_ID, uploadingProgressNotification(String.valueOf(current_image_uploading+1), percent + 10));
}
uploaded += read;
sink.write(buffer, 0, read);
}
}
Log.d(TAG, "writeTo: test");
即使它应该只有 10 次,它仍然被调用了很多次。
IntentService[n identical 346 lines
解决方案
使用以下代码:
int percent = (int) (100 * uploaded / fileLength);
if(percent % 10 == 0 && lastPercent != percent){
lastPercent = percent;
mManager.notify(NOTIFICATION_ID, uploadingProgressNotification(String.valueOf(current_image_uploading+1), percent));
}
还创建全局变量public int lastPercent = 0;
推荐阅读
- sql - SQL查询;返回主表的所有记录,并在条件下从连接表中添加字段;在连接表中找不到匹配项时将值留空
- c# - JsonHttpContent 与 ASP.NET Core 3.1
- html - 正确 mat-ccard-header 中的 mat-card-avatar 图像高度
- ibm-mq - 使用 Splunk 解析 IBM MQ v9.1 错误日志
- flutter - Flutter:所有页面上的弯曲底部导航栏并从主页开始
- c - 我正在尝试提高我的互相关算法的性能速度。我可以做些什么来让我的 C 代码运行得更快?
- qt - 具有 QML 和 C++ 后端的 QtDataVisualization 应用程序 - 可能吗?
- php - 复制文件后更改 php 内容
- c# - HasAttributes和xml文件的C#问题
- javascript - 将其用于 DIV 时无法读取未定义的属性“classList”