我所做的是将通知存储在类级变量中。也许将您的函数更改为 createDownloadNotification 并使用上面的内容,除了使通知成为整个类都可以访问的变量。
然后有另一个函数(类似于 updateDownloadNotification),它将使用更新的信息在通知上调用 setLatestEventInfo。
另请注意,您需要调用 mNotificationManager.notify(HELLO_ID, notification); 每次更新后,否则什么都不会改变。
---更新---实际上你可以只有1个功能并检查通知是否为空(如果不是,创建它)否则使用你已经拥有的。
例子:
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);
}