I’m currently working on implementing a chat application using Firebase Cloud Messaging and facing difficulties architecting it to handle offline scenarios.
Here’s what I aim to achieve: When my app is closed or not running (even in the background) and the internet connection is off, upon receiving a new notification from a sender, I want to cache or store it in the database. Later, when I open my app without an internet connection, I should be able to see all the received messages.
Here’s what I’ve implemented so far:
MyFirebaseMessagingService.kt
val TAG = "FSNotifi"
private val PREFS_NAME = "MyPrefsFile"
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val prefs: SharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor = prefs.edit()
// Check if message contains a notification payload.
remoteMessage.notification?.let {
editor.putString("FSNoti", it.body.toString())
editor.apply()
Log.d(TAG, "Message Notification Body: ${it.body}")
}
}
}
AndroidManifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Despite this setup, the message doesn’t seem to be stored in SharedPreferences. I’m seeking guidance on how to properly achieve this task. Is there a better approach or a step I might be missing in implementing this offline message storage functionality using Firebase Cloud Messaging?
Any help or advice would be greatly appreciated. Thank you!
PS: I found answer of my question
Userful Link: How to handle notification when app in background in Firebase
I think you should use
Room
Database for storing it offline for later use.You are right @ChiragThummar but I will store in room once it gets stored in sharedpreference
No when notification is received you can save data in room and you can use it later as you wish
@ChiragThummar I meant to say just for testing I am storing in sharedpreference
I think that this resource will help. Here is the corresponding repo.