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

时间:2012-07-18 15:03:28

标签: android notifications

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

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

我在android-developers中找到了这个:“你可以用对象成员字段修改每个属性(Context和通知标题和文本除外)。”这是否意味着我无法获取contentText?如果我无法得到它,我应该将数字保存在静态类或类似的东西中吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

我可能会迟到回答您的问题,但这里是您如何将其与某种解决方法集成:

(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中,每次收到新邮件时都会使用设置者增加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

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

答案 1 :(得分:-1)

您可以使用通知方法,使用与旧通知相同的通知ID

  

public void notify(String tag,int id,Notification notification)   自:API等级5   发布要在状态栏中显示的通知。如果您的应用程序已经发布了具有相同标记和ID的通知但尚未取消,则它将被更新的信息替换。