Skip to content

Instantly share code, notes, and snippets.

@riggaroo
Last active July 15, 2020 12:30
Show Gist options
  • Save riggaroo/90650d556a2e2c0d03e293b7f5d4c67e to your computer and use it in GitHub Desktop.
Save riggaroo/90650d556a2e2c0d03e293b7f5d4c67e to your computer and use it in GitHub Desktop.
Online Presence with Firebase and Android based off article https://firebase.googleblog.com/2013/06/how-to-build-presence-system.html . Read the article as it explains the whole .onDisconnect().removeValue() nicely.
private void initialiseOnlinePresence() {
final DatabaseReference onlineRef = databaseReference.child(".info/connected");
final DatabaseReference currentUserRef = databaseReference.child("/presence/" + userId);
onlineRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(final DataSnapshot dataSnapshot) {
Log.d(TAG, "DataSnapshot:" + dataSnapshot);
if (dataSnapshot.getValue(Boolean.class)){
currentUserRef.onDisconnect().removeValue();
currentUserRef.setValue(true);
}
}
@Override
public void onCancelled(final DatabaseError databaseError) {
Log.d(TAG, "DatabaseError:" + databaseError);
}
});
final DatabaseReference onlineViewersCountRef = databaseReference.child("/presence");
onlineViewersCountRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(final DataSnapshot dataSnapshot) {
Log.d(TAG, "DataSnapshot:" + dataSnapshot);
onlineViewerCountTextView.setText(String.valueOf(dataSnapshot.getChildrenCount()));
}
@Override
public void onCancelled(final DatabaseError databaseError) {
Log.d(TAG, "DatabaseError:" + databaseError);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment