I have created this chat application with firebase realtime database and firebase authentication methods but i am really confused and I don\'t exactly know how to get the la
The last seen feature that you are asking for is also known as a presence system
. The good news is that you can find in the Firebase Real-time database a method named onDisconnect()
that can help you achieve this. When you attach a handler to the onDisconnect()
method, the write operation you specify will be executed on the server when that server detects that the client has disconnected.
Here you can find the official documentation for how to manage the presence system.
This is actually how it looks like in code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("disconnectmessage");
// Write a string when this client loses connection
rootRef.onDisconnect().setValue("Disconnected!");
This is a straightforward example of writing data upon disconnection by using the onDisconnect
method.
To solve the entire seen feature
for Firebase, you should add to each user two new properties. The first one would be isOnline
and is of type boolean and the other one is a timestamp
which is map
. If you want to display if a user is online/offline, it is as simple as:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference isOnlineRef = rootRef.child("users").child(uid).child("isOnline");
onlineRef.setValue(true);
onlineRef.onDisconnect().setValue(false);
For the second property, please see my answer from this post, where I have exaplained how you can save and retrive the timestamp from a Firebase Real-time database. To display the time from the last seen, just make a difference between the current timestamp and the timestamp from your database.
Note that this will work in simple cases, but will start to have problems, for istance when the connection toggles rapidly on user's device. In that case it may take the server more time to detect that the client disappears (since this may depends on the socket timing out) than it takes the client to reconnect, resulting in an invalid false
.
To handle these kind of situations, please take a look at the sample presence system in the official documentation, which has more elaborate handling of edge cases.
One more thing to note is that the server can detect the disconnecting of a client in two ways:
When it's a clean disconnect (the app closes cleanly, it calls goOffline()
), the client sends a message to the server, which can then immediately execute the onDisconnect() handlers.
When it's a so-called dirty disconnect
(you drive into a tunnel and lose signal, the app crashes), the server only detects that the client is gone once the socket ties out, which can take a few minutes. This is the expected behavior, and there is no better alternative that I've learned so far.