I am developing an Android App, I using firebase push notifications, I want onMessageReceived() should save the notifications data into the shared preferences, so that in future I'll show a list view where user will be able to see all the notifications.
Issue: My issue is sometimesAPP is saving the notification to sharedPrefs and sometimes not, And If i receive notification in background then it never saves to shared prefs.
I did the following implementation:
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
if(remoteMessage.getNotification() != null){
Log.d(TAG, "onMessageReceived: Printing Message details: ");
Log.d(TAG, "Title: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "Message Body: " + remoteMessage.getNotification().getBody());
if (remoteMessage.getData().size() > 0) {
Map<String, String> msgData = remoteMessage.getData();
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
Notification notification;
String title = remoteMessage.getNotification().getTitle();
String msg = remoteMessage.getNotification().getBody();
notification = new Notification(title, msg);
ArrayList<Notification> notificationsList = AppData.getInstance(getApplicationContext()).getNotifications();
notificationsList.add(notification);
AppData.getInstance(getApplicationContext()).setNotifications(notificationsList);
generateNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getImageUrl());
}
Notification.java
public class Notification {
String msgTitle;
String msgBody;
String imageURL;
String time;
Boolean read = false;
public Notification(String msgTitle, String msgBody) {
this.msgTitle = msgTitle;
this.msgBody = msgBody;
}
}
AppData is a singleton class, which is saving data in shared preferences.
AppData method I'am using:
public ArrayList<Notification> getNotifications() {
SharedPrefrences.init(context);
Gson gson = new Gson();
String json = SharedPrefrences.read(Constants.E_NOTIFICATIONS, "");
if(json == "") return null;
Notification[] notifications = gson.fromJson(json, Notification[].class);
ArrayList<Notification> notificationArrayList = new ArrayList<>();
notificationArrayList.addAll(Arrays.asList(notifications));
return notificationArrayList;
}
public void setNotifications(ArrayList<Notification> notifications) {
this.notifications = notifications;
SharedPrefrences.init(context);
Gson gson = new Gson();
String json = gson.toJson(notifications);
SharedPrefrences.write(Constants.E_NOTIFICATIONS, json);
}