在 Android 中更新通知文本(取决于以前的值)



我正在实现一个接收消息并在收到消息时通知您的应用程序。我想实现一个类似Whatsapp的通知系统:如果我只收到一条消息,消息的标题将显示在通知中;如果我收到另一条消息,通知必须说我有两条消息,以此类推。

我想获得通知的前一个contentText,以便能够知道用户到目前为止收到了多少条消息,然后将现在收到的消息数量添加到其中,但我找不到如何获得它。

我在android开发者中发现了这一点:"你可以用对象成员字段修改每个属性(上下文和通知标题和文本除外)。"这是否意味着我无法获得contentText?如果我不能得到它,我应该把这个数字保存在一个静态类或类似的东西中吗?

谢谢!

我可能会迟到回答您的问题,但以下是如何将其与一种变通方法集成:

(1) 在您的应用程序中,您需要一个统计"未读消息"的变量。我建议您集成一个扩展android.app.Application的类。这有助于全局处理变量,例如在多个活动中。这里有一个例子:

import android.app.Application;
public class DataModelApplication extends Application {
    // model
    private static int numUnreadMessages;
    // you could place more global data here, e.g. a List which contains all the messages
    public int getNumUnreadMessages() {
        return numUnreadMessages;
    }
    public void setNumUnreadMessages(int numUnreadMessages) {
        this.numUnreadMessages = numUnreadMessages;
    }
    ...
}

不要忘记将应用程序添加到您的AndroidManifest:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:name="name.of.your.package.DataModelApplication" >
    <activity ... />
    ...
</application>

(2) 在您的ActivityFragment中,每次收到新消息时,您都可以使用setter来增加numUnreadMessages,例如:

// within a Fragment you need to call activity.getApplication()
DataModelApplication application = (DataModelApplication) getApplication();
int numUnreadMessages = application.getNumUnreadMessages();
application.setNumUnreadMessages(++numUnreadMessages);

(3) 现在,您可以使用未读消息的数量更新通知,例如

// within your service or method where you create your notification
Intent mainActivityIntent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, mainActivityIntent, 0);
DataModelApplication application = (DataModelApplication) getApplication();
int numMessages = application.getNumUnreadMessages();
// build the notification
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
String contentTitle = "You have " + numMessages + " unread message(s)";
String contentText = "Click here to read messages";
Builder notifyBuilder = new NotificationCompat.Builder(this)
    .setContentTitle(contentTitle)
    .setContentText(contentText)
    .setContentIntent(pIntent)
    .setAutoCancel(true)
    .setNumber(numMessages) // optional you could display the number of messages this way
    .setSmallIcon(R.drawable.ic_launcher);
notificationManager.notify(notifyID, notifyBuilder.build());

(4) 每次用户阅读消息或单击通知打开"活动"时,不要忘记重置或递减numUnreadMessages的值。它类似于步骤(2),但会递减该值或将其设置为0

希望这能帮助你/任何人开始:)

您可以使用notify方法,该方法具有与旧通知相同的通知id

public void notify(字符串标记,int id,通知通知)自:API 5级张贴要显示在状态栏中的通知。如果您的应用程序已经发布了具有相同标签和id的通知,但尚未取消,则该通知将被更新的信息所取代。

最新更新