Guest User

Untitled

a guest
Nov 25th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. // since I can connect from multiple devices, we store each connection instance separately
  2. // any time that connectionsRef's value is null (i.e. has no children) I am offline
  3. final FirebaseDatabase database = FirebaseDatabase.getInstance();
  4. final DatabaseReference myConnectionsRef = database.getReference("users/joe/connections");
  5.  
  6. // stores the timestamp of my last disconnect (the last time I was seen online)
  7. final DatabaseReference lastOnlineRef = database.getReference("/users/joe/lastOnline");
  8.  
  9. final DatabaseReference connectedRef = database.getReference(".info/connected");
  10. connectedRef.addValueEventListener(new ValueEventListener() {
  11. @Override
  12. public void onDataChange(DataSnapshot snapshot) {
  13. boolean connected = snapshot.getValue(Boolean.class);
  14. if (connected) {
  15. DatabaseReference con = myConnectionsRef.push();
  16.  
  17. // when this device disconnects, remove it
  18. con.onDisconnect().removeValue();
  19.  
  20. // when I disconnect, update the last time I was seen online
  21. lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);
  22.  
  23. // add this device to my connections list
  24. // this value could contain info about the device or a timestamp too
  25. con.setValue(Boolean.TRUE);
  26. }
  27. }
  28.  
  29. @Override
  30. public void onCancelled(DatabaseError error) {
  31. System.err.println("Listener was cancelled at .info/connected");
  32. }
  33. });
Add Comment
Please, Sign In to add comment