Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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");
- }
- });
Add Comment
Please, Sign In to add comment