我可能会迟到回答您的问题,但是您可以通过以下方式将其与一种解决方法集成:
(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) 在您Activity
或您每次收到新消息时使用 setterFragment
递增,例如: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) 每次用户阅读消息或用户通过单击该通知打开 Activity 时,不要忘记重置或减少 numUnreadMessages 的值。它与步骤 (2) 类似,但将值递减或将其设置为0
.
希望能帮助你/任何人开始:)