我运行的服务,通过startForeground(int id, Notification notification
配置为前台服务),我想更新此通知。我的代码实现如下:
private void setForeground() {
Notification foregroundNotification = this.getCurrentForegroundNotification();
// Start service in foreground with notification
this.startForeground(MyService.FOREGROUND_ID, foregroundNotification);
}
...
private void updateForegroundNotification() {
Notification foregroundNotification = this.getCurrentForegroundNotification();
// Update foreground notification
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MyService.FOREGROUND_ID, foregroundNotification);
}
根据服务状态生成通知:
private Notification getCurrentForegroundNotification() {
// Set up notification info
String contentText = ...;
// Build notification
if (this.mUndeliveredCount > 0) {
String contentTitleNew = ...;
this.mNotificationBuilder
.setSmallIcon(R.drawable.ic_stat_notify_active)
.setContentTitle(contentTitleNew)
.setContentText(contentText)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_stat_notify_new))
.setNumber(this.mUndeliveredCount)
.setWhen(System.currentTimeMillis() / 1000L)
.setDefaults(Notification.DEFAULT_ALL);
} else {
this.mNotificationBuilder
.setSmallIcon(R.drawable.ic_stat_notify_active)
.setContentTitle(this.getText(R.string.service_notification_content_title_idle))
.setContentText(contentText)
.setLargeIcon(null)
.setNumber(0)
.setWhen(0)
.setDefaults(0);
}
// Generate Intent
Intent intentForMainActivity = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intentForMainActivity, 0);
// Build notification and return
this.mNotificationBuilder.setContentIntent(pendingIntent);
Notification foregroundNotification = this.mNotificationBuilder.build();
return foregroundNotification;
}
问题是我的通知无法正确更新:当我启动服务以在前台运行时,使用updateForegroundNotification()
多次调用this.mUndeliveredCount > 0
,然后使用{{1}再次调用this.mUndeliveredCount == 0
},即使没有提供大图标,通知右下角的小通知图标也不会消失。根据{{1}}类的documentation of the setSmallIcon(int icon)
方法,这种行为并不是完全可以预料的,如果指定了一个大图标,则小图标应该只显示在右下角:
NotificationBuilder
设置小图标资源,该资源将用于表示状态栏中的通知。展开视图的平台模板将在左侧绘制此图标,除非还指定了大图标,在这种情况下,小图标将移动到右侧。
在更新服务通知时我做错了什么?或者这是Android的错误吗?
答案 0 :(得分:0)
在确定这不是我的错误导致不需要的小通知图标后,我搜索并找到了上述错误的简单解决方法:
通过Notification
方法更新updateForegroundNotification()
时,我会通过“重置”通知生成并更新我的通知ID。 “重置”通知配置如下:
this.mNotificationBuilder
.setSmallIcon(0)
.setContentTitle("Reset")
.setContentText("Reset")
.setLargeIcon(null)
.setNumber(0)
.setWhen(0)
.setDefaults(0);
通过这样的通知,我打电话给
Notification resetForegroundNotification = this.getResetForegroundNotification();
this.mNotificationManager.cancel(MyService.FOREGROUND_NOTIFICATION_ID);
this.mNotificationManager.notify(MyService.FOREGROUND_NOTIFICATION_ID, resetForegroundNotification);
在执行预期的通知更新之前,不需要的右下角图标在下一个仅设置小图标的通知中消失。