我有一项服务,可以在不同的线程中同时执行多次下载。对于每次下载,都会显示带有进度的通知。进度每秒更新一次。如果您同时运行三个或更多下载,当您更新通知时,他们会随机更改状态栏中的位置,跳过另一个。
我尝试设置优先级setPriority (priority)
,我使用setOnlyAlertOnce (true)
,但这没有帮助。与此同时,在其他一些应用程序中,我看到通知在他们的位置更新。
问题是,如何实现这一目标?
目前,我的通知创建如下:
private LongSparseArray<Task> mTasksArray = new LongSparseArray<>();
private int notifyId = 0;
...
//setup notification id on task download start
private void initTask(long taskId) {
Task task = new Task();
...
task.setNotificationId(notifyId++);
mTasksArray.put(taskId, task);
}
...
//notification update, called about once a second for every running download
private void showNotify(Task task) {
int notificationId = task.getNotificationId();
Notification notification = getProgressNotification(task);
mNotifyManager.notify(notificationId, notification);
}
@NonNull
private Notification getProgressNotification(Task task) {
int max = task.getTotal();
int count = task.getCount();
/**
* using id of notification as priority, but actual priority values can be only from -2 to 2
* right now it can show three first downloads correctly (for id values 0,1,2), but if,
* for example, stop first task and start another one, next id and priority will be 3
* (actually priority will be 2, because max priority is 2) and 3th and 4th notifications
* will reorder on every update, because of same priority
*/
int priority = task.getNotificationId();
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, CHANNEL_ID);
builder.setContentTitle(mContext.getString(R.string.notif_title_downloading))
.setOnlyAlertOnce(true)
.setOngoing(true)
.setPriority(priority)
.setSmallIcon(R.drawable.ic_file_download_white_24dp)
.setProgress(max, count, false)
.addAction(getPauseAction(task))
.addAction(getStopAction(task))
.setContentText(String.format(Locale.ENGLISH, "%d/%d", count, max));
return builder.build();
}
更新
答案 0 :(得分:5)
您需要为每个后续更新使用相同的通知构建器。例如:
//First time
NotificationCompat.Builder builder = new NotificationCompat.Builder(...)
...
notificationManager.notify(id, builder.build());
//Second time
builder.setProgress(max, count, false);
notificationManager.notify(id, builder.build());