【发布时间】:2015-02-14 11:22:34
【问题描述】:
我有一个可以接收通知(使用 Google Cloud Messaging)并通知用户的服务。在该服务中,我还使用 SharedPreferences 存储云消息传递发送的消息。我将这些消息收集在一个 HashSet 中,并且该 HashSet 及其任何元素都不应该被删除。这很重要,因为我的一项活动必须显示整个消息列表。
这工作正常,除非用户碰巧使用“最近的应用程序”按钮来终止应用程序。当他这样做然后重新启动应用程序时,活动没有检索到一些消息,所以我猜其中一些消息已经以某种方式被删除了。
我没有正确使用 SharedPreferences 吗?我应该怎么做才能避免这种情况?这是我的服务代码:(我的 onHandleIntent 方法的相关部分)
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Notifications.class), 0);
String message=extras.getString("message");
sharedpreferences=this.getSharedPreferences(Constantes.PREFERENCES,Context.MODE_PRIVATE);
Set<String> setMessages= sharedpreferences.getStringSet("SETMESSAGES", new HashSet<String>());
setMessages.add(message);
Editor editor = sharedpreferences.edit();
editor.putStringSet("SETMESSAGES", setMessages);
editor.commit();
//The notification:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("New Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText("You got some new message!"))
.setContentText("You got some new message!")
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
【问题讨论】:
-
之前 editor.putStringSet("SETMESSAGES", setMessages);调用 editor.clear();
-
是您在“静态”方法中提到的上述代码吗?如果是这样,则很少有已知问题,在此链接中讨论。stackoverflow.com/questions/11480871/…
-
@MeTechnical 不是在静态方法中,这段代码是在onHandleIntent()方法中,还是在onHandleIntent()调用的非静态方法中。 (哪个签名是私有的 void sendNotification(Bundle extras)
-
@Ramesh 看来您的解决方案有效,非常感谢。您是如何找到该解决方案的?如果你愿意,可以回答我的问题,我会选择它作为正确答案。
-
@Kritias 在 SP 中存储消息(实际上是任何频繁更改的数据)并不理想,也不建议使用。相反,您可以为此使用 SQLite 或 Realm,例如 Db。 SP用于存储少量偶尔变化的信息,写SP是一项繁重的操作。
标签: android sharedpreferences google-cloud-messaging