Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain the presence status of user in firebase Android

Tags:

java

android

I am developing a chat app in which i have to maintain the user online status and the technology i am using is firebase so how can i do that any kind of help is appreciated. Thanks in advance...

like image 586
kishan sahu Avatar asked Dec 24 '22 18:12

kishan sahu


1 Answers

Mabz has the right idea conceptually, but I want to highlight a feature of Firebase that specifically addresses your use case.

The trouble that I had run into was updating the RealtimeDatabase with an 'Offline' status. That is, If the client (e.g. your Android app) is offline, how is it supposed to tell the database?

The Solution: Use DatabaseRef.onDisconnect() to set offline status automatically

DatabaseRef presenceRef = 
FirebaseDatabase.getInstance().getReference("disconnectmessage");
// Write a string when this client loses connection
presenceRef.onDisconnect().setValue("I disconnected!");

From the documentation:

When you establish an onDisconnect() operation, the operation lives on the Firebase Realtime Database server. The server checks security to make sure the user can perform the write event requested, and informs the your app if it is invalid. The server then monitors the connection. If at any point the connection times out, or is actively closed by the Realtime Database client, the server checks security a second time (to make sure the operation is still valid) and then invokes the event.

A (slightly) more practical example might do something like this when your app first connects:

DatabaseRef userStatus = 
FirebaseDatabase.getInstance().getReference("users/<user_id>/status");
userStatus.onDisconnect.setValue("offline");
userStatus.setValue("online");

NOTE: Please note the order of the last two "online" and "offline" status lines. Do not swap it, or else you might have "ghost users" in case the onDisconnect handler fails to register due to a disconnect itself. (which is actually a race condition problem)

like image 105
darkpbj Avatar answered Mar 08 '23 23:03

darkpbj