Firebase push notifications for users with specific firestore fields - android

I'm currently making a chatroom-like app that works with firestore to connect users to a host's session. I ran into a problem where client devices lose connection / stop listening for firestore changes when locked/backgrounded for too long (to my knowledge it's because the device tries to save power by killing long-living processes). I learned that a workaround would be to send a FCM push notification to devices prior to changing the firestore doc so it'd reawaken the app and have the app listen for the firestore doc change. I'm not sure how to implement push notifications, but I learned that it requires a user specific token (that must be protected). Ignoring the fact that I'm not sure how to implement push notifications (noob-friendly pointers would be appreciated), would uploading the user token to firestore as a field be a viable approach? I'm thinking that I can use my helper function (which gets all non-hosts of a specific session) to also send push notifications to each person.
_vibrateAllDevices() async {
var lobbies = await lobby
.where('lobbyCode', isEqualTo: _lobbyCode)
.where('userRole', isEqualTo: 2)
.get();
lobbies.docs.forEach(
(document) async {
document.reference.update(<String, dynamic>{'vibrate': true});
},
);
}
Each lobby is expected to have anywhere from 2-30 people so looping per person doesn't seem to be that big of an issue. Does this seem like a viable approach or is storing tokens to firestore an unsafe? I should also mention that each lobby is expected to only be opened for a short amount of time (~3 hours max) and all information is deleted right after.

Firebase through notification if another subscribe to your own topic make sure that another person subscribes the topic when Firestore field is created. When you trigger notification then automatically receive notification in another person in FirebaseMessages service class in which method onmessagereceive.
There is the same way to trigger a notification in firebase and Firestore because server key always same.
I recommended you to read this documentation:
https://medium.com/mindorks/send-device-to-device-push-notification-using-firebase-cloud-messaging-without-using-external-769476c79ffd

Related

I want to be notified when data is added in Firebase Realtime Database

I have an application with two different package names. There are separate databases for these two applications. If a user adds new data, I want to receive a message. (For example: Added new data to app A or new data added to app B) I don't want to constantly check. How can I do that?
I can receive notifications as Mail, or I can make a different application and an application that controls the content of these two applications. But I don't know how to make notifications.
To display notification to a user about a change in the data while they are not actively using the app, you'll typically use Firebase Cloud Message or some other out-of-band mechanism to deliver the message.
To detect the relevant data change and send that message, you'll want to run code in a trusted environment that is guaranteed to continue to run all the time. An example of such an environment is Cloud Functions, which also has an example of notifying the user when something interesting happens.
You can use cloud functions to trigger events when there are document changes.
Docs are here : https://firebase.google.com/docs/functions/firestore-events.
Then you can tie those triggers with FCM to get notified when doc changes.

Send notifications to user in android studio

I want to build a notification system in my Android app where I can send a notification to someone upon an event. For example, my app is about a social system where it uses Firestore database (Firebase) to save its users (which means I have a 'users' collection in there), and I have an 'Add as Friend' feature.
Everything works just fine, but I would like to add a feature where when user1 adds user2 as a friend, I would like to send user2 a notification about that.
I have searched in google and saw this post: https://www.geeksforgeeks.org/how-to-push-notification-in-android-using-firebase-cloud-messaging/
Now, from what I understand, this wouldn't help me much cause it only sends the notification from FCM by me (and not to a specific user).
The problem is, I don't really know what to search for (or what to type in google) in order to find what I'm looking for.
Some ideas I thought:
to make a collection in firestore called 'Notifications' where it holds usernames as documentIDs
when user1 sends a friend request to user2, I would add data (like title/message) to 'Notifications/user2/'
But I'm kind of stuck here, I would like to know ideas or if you guys have threads on how do I implement this, I really don't know what should I look for.
Thank you very much and sorry for the long post.
Firebase creates a userID for every user and a usertoken which is a temporary identifier for the device which is connected to this userID. You need to save the usertoken when there is a new one being created in a database(firestore) along with the user with whom you identify this person.
When someone adds this person as a friend you can add a notification in the database that there is a request from person1 to person2.
This change in the database can trigger a cloud function that reacts to changes in the database.
The triggered cloud function sends an FCM to the person which is being added as a friend. This FCM can either be a pure notification or you send data and let your app handle how this data is being handled(saved in a local database or displayed as a custom notification).
Keywords are: FCM, Notification, Firestore, cloud functions, and firebase token
Edit (Answer to 1. comment): Firebase userID and usertoken are created on the device. In the tutorial you implement FCM(I didn't read it complete) and a class called FirebaseMessagingService, from which you can inherit. This class is called, when a message is sent to the device and contains a method called onNewToken. This message is called, when the Firebase Server creates a token for your device and sends it to the device. In this method you might want to send the new token to your database and save it as an identifier for the user of this device. The Tokens are used by firebase to identify devices, to which messages are being sent(You can read about FCM in detail)
Cloud functions are something you can deploy along your firebase project, which get triggered when an event occurs. For example a http call, or a specific change in your database. Cloud functions are written in JS and need to be deployed for your firebase project. (Cloud functions are not for free and you need to pay for each call, but you have some thousand uses for free each month.)
You send a FCM to a specific person by creating a firebase message which is directed to a specific token, tokens or user groups. To identify the person to which you want to send a message you need to have the token for this user, that is why you are saving the tokens from the 1. part in your database and always update the token, when the token changes on the device.
Keep in mind, that a user might use multiple devices. You should have an identifier for you, such as username and along this username you save multiple firebaseIds and Firebase tokens. A single FCM can be directed to up to 100 tokens.

Firebase Cloud Function : Send notification to all user using sendToDevice()

I am already using Cloud Messaging feature in Firebase and utilized the sendToTopic() legacy method of sending notification to all subscribers but I've seen a limitation using topic in my app. Now I want to manage my way of sending and receiving notification by sending notification to each device using the registered device token in user's document which stored as map object. I will iterate to each device token and use sendToDevice() to send notification to each device.
I have now a function lets call it new_added that triggers whenever new document is added in a collection. Now every time new_added function gets called, this will iterate to each document in Users collection and write a new document under Notification collection. The structure would be this Users (collection) > uid (document) > Notifications > doc. Every new added item under Notification collection will trigger a function in server. This operation is too heavy specially if there is a million number of users, does this kind of operation can be perform in server side using Cloud Function within 540 seconds which is said to be the maximum runtime of a function after gets trigger? I really want it to work this way. Is there any tool that will help to minimize the operation?
If sounds like you're trying to implement your own FCM messaging fan-out, sending the same message to many users. This is similar to what FCM topic messaging already does, to I'd definitely consider using that for the moment.
But if you want to implement it yourself, consider how to optimize it for the underlying system. Since you're storing the tokens in Firestore, the number of documents you read is a key factor in the cost.
A way to reduce the number of documents you read could be to store the tokens for a group of devices into a single document. For example, you could create a document for each "topic", and add tokens to that doc as they are written to the database. Then when you need to send a message to all devices for a topic, you simply read that topic-document, and get all tokens in one go. This becomes especially simple if you name the document after the topic for which it contains the tokens, e.g. mytopic-tokens.
The main problem with this approach is that a document can be no bigger than 1Mb. Say that tokens are at most 256 bytes (they seem to be 152-162 characters), you can store 4000 tokens in a document. If you have more tokens, you will need to create multiple documents. A simple naming scheme can go a long way here, such as mytopic-tokens-1, mytopic-tokens-2, etc. You can get all these documents with a single range-query in Firestore.

Using FCM token for signIn instead of user email

I don't want to have login or signup for my app. I've implemented fire-base notification in the app as well.
Can I use Fire-base FCM ID (token) as a unique user identifier. Instead of creating a user in the system I'll create a FCM table(id(pk), FCMID) and store all information of the user against that FCM id.
If yes then at what instance it changes the FCM id.
You can but you shouldn't
FCM token can change if you see the Service used for getting the FCM token, the one that has to extend FirebaseInsanceIdService the method inside is called onTokenRefresh() because it will be triggered every time the FCM token is refreshed for a new one. In previous Google Cloud Messaging (GCM) this strike to me as erratic, but in current FCM it seems to be infrequent.
You could do this by saving the current token in some form of local persistence (sharedpreference, database, etc). Then when the FCM is refreshed using the stored FCM the nodes in the real-time database can be updated.
This will have some bad scenarios: what happens if the user re-login by reinstalling or changing device? The first can be solved by saving something unique in the device, I have seen that some sort of devices ids can be get, but those are reset after boot or factory reset. Then a more general solution would make the user to input something unique to them every time they log in. It could be the email, or it could be the phone number.
Which leads me to, use phone authentication instead
i hope tis is helpful to
this is mydb in fcm
db structure in json like,
walinnstracker{
active_users{
info{
"count" : "13",
"female_count" : "0"
"male_count" : "0"
}
}
}

How to determine if a device with a specific token is online with firebase android?

I was wondering how it is possible to determine if a device with token 'A' is online with another android device using firebase framework?
When app starts, you can use https://www.firebase.com/docs/web/api/ondisconnect/remove.html to make sure that a specific data is removed when client comes offline. Then you can, somewhere else, see if that data is there (still online) or not (now offline).
This page https://www.firebase.com/docs/web/api/ondisconnect/ states the following
The onDisconnect class allows you to write or clear data when your
client disconnects from the Firebase servers. These updates occur
whether your client disconnects cleanly or not, so you can rely on
them to clean up data even if a connection is dropped or a client
crashes.
The onDisconnect class is most commonly used to manage presence in
applications where it is useful to detect how many clients are
connected and when other clients disconnect. See Offline Capabilities
for more information.
Let´s say you have a list of online users in your db. Something like this:
onlineUsers: {
user1: true,
user23: true,
user100: true
}
The example illustrates that users user1, user23 and user100 are online. Let´s say user23 comes online and you want the firebase db to reflect if that user is online or not, do this:
var disconnectRef = new Firebase('https://<YOUR-FIREBASE-APP>.firebaseio-demo.com/onlineUsers/user23');
disconnectRef.onDisconnect().remove();
The above code does not remove anything at execution. It just tells the Firebase server to remove onlineUsers/user23 when client comes offline.
As soon as that client (say Android app/device) comes offline, the Firebase servers will make sure that the new state will be like this:
onlineUsers: {
user1: true,
user100: true
}
As you can see, user23 is no longer present in the list.

Categories

Resources