我正在使用通知管理器进行内容下载并显示已完成下载的百分比,但每次使用新百分比调用displaymessage函数时,它都会创建新通知。如何在不创建新通知的情况下更新通知?
public void displaymessage(String string) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = "Shamir Download Service";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "Downloading Content:";
notification.setLatestEventInfo(context, contentTitle, string, null);
final int HELLO_ID = 2;
mNotificationManager.notify(HELLO_ID, notification);
}
答案 0 :(得分:1)
我所做的是将通知存储在类级变量中。 也许将您的函数更改为createDownloadNotification并使用上面的内容,除了使通知成为整个类可访问的变量。
然后有另一个函数(类似于updateDownloadNotification),它将使用更新的信息调用通知上的setLatestEventInfo。
另请注意,您需要调用mNotificationManager.notify(HELLO_ID,通知);每次更新后或没有任何改变。
---更新--- 实际上你可以只有一个函数并检查通知是否为空(如果没有,创建它),否则使用你已经拥有的。
示例:
public class YourClass extends Service { //or it may extend Activity
private Notification mNotification = null;
public void displaymessage(String string) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = "Shamir Download Service";
long when = System.currentTimeMillis();
if (mNotification == null) {
mNotification = new Notification(icon, tickerText, when);
}
//mNotification.when = when;//not sure if you need to update this try it both ways
Context context = getApplicationContext();
CharSequence contentTitle = "Downloading Content:";
notification.setLatestEventInfo(context, contentTitle, string, null);
final int HELLO_ID = 2;
mNotificationManager.notify(HELLO_ID, mNotification);
}
我的代码实际上有点不同,因为我正在更新的是每次更新时通知的iconLevel,所以我不确定每次更改是否需要更新mNotification.when
尝试并查看并报告。
此外,我还会从这个函数中做出一些变量。如果它是类的私有实例变量,通常可以命名变量mSomething。以下是我的建议:
private Notification mNotification = null;
private NotificationManager mNotificationManager = null;
private static final int HELLO_ID = 2;
public void displaymessage(String string) {
String ns = Context.NOTIFICATION_SERVICE;
if (mNotificationmanager == null) {
mNotificationManager = (NotificationManager) getSystemService(ns);
}
int icon = R.drawable.icon;
CharSequence tickerText = "Shamir Download Service";
long when = System.currentTimeMillis();
if (mNotification == null) {
mNotification = new Notification(icon, tickerText, when);
}
//mNotification.when = when;//not sure if you need to update this try it both ways
Context context = getApplicationContext();
notification.setLatestEventInfo(context, contentTitle, string, null);
mNotificationManager.notify(HELLO_ID, mNotification);
}