I'm using FCM to send my users app notification, I also store user status(which is logged in or not) using shared preferences. when I send notification to my users all of them will receive message, how can I prevent receiving message for users who are not logged into app?
2 Answers
You should send data message which can be processed from your FCMService
class. Hence you can show the notification from onMessageReceived
conditionally.
Refer this documentation to send data notifications.

- 141
- 5
Atleast add some code for better suggestion, but here is what you can do to make sure that only those users who are logged in receive the notifications. Since notifications are created by you only so you can control them as well.
Add below logic in your Service class which extends FirebaseMessagingService.
for example.
override fun onMessageReceived(message: RemoteMessage) {
// this is where you receive your notifications.
//just before showing messages just check if user us logged in or not
if(!sharedPreference.isLoggedIn()) return
//if he is logged in, your notification showing code goes below.
}
edit:
in case of app is not in foreground then onMessageReceived won't get called if you are sending notification payload in that case from server make sure to send only data payload not notification object and then it will get called onMessageReceived and based on received payload check if the user is loggedin or not based on that show notification.
please read this thread for more clarification.

- 10,447
- 2
- 46
- 52
-
this method just will be called when user is in app and application is open not when its in background @vikaskumar – mohammad Aug 20 '20 at 13:38