Created
November 23, 2017 13:06
-
-
Save benhaxe/7efa24950bea14b8b41190f698d404c9 to your computer and use it in GitHub Desktop.
Still on firebase real time database, the code helps track when a user is online or not and also the last time a user is seen.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// since I can connect from multiple devices, we store each connection instance separately | |
// any time that connectionsRef's value is null (i.e. has no children) I am offline | |
final FirebaseDatabase database = FirebaseDatabase.getInstance(); | |
final DatabaseReference myConnectionsRef = database.getReference("users/joe/connections"); | |
// stores the timestamp of my last disconnect (the last time I was seen online) | |
final DatabaseReference lastOnlineRef = database.getReference("/users/joe/lastOnline"); | |
final DatabaseReference connectedRef = database.getReference(".info/connected"); | |
connectedRef.addValueEventListener(new ValueEventListener() { | |
@Override | |
public void onDataChange(DataSnapshot snapshot) { | |
boolean connected = snapshot.getValue(Boolean.class); | |
if (connected) { | |
DatabaseReference con = myConnectionsRef.push(); | |
// when this device disconnects, remove it | |
con.onDisconnect().removeValue(); | |
// when I disconnect, update the last time I was seen online | |
lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP); | |
// add this device to my connections list | |
// this value could contain info about the device or a timestamp too | |
con.setValue(Boolean.TRUE); | |
} | |
} | |
@Override | |
public void onCancelled(DatabaseError error) { | |
System.err.println("Listener was cancelled at .info/connected"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment