问题
I am building a chatapp using firebase database. I need to show online users, how can I do that? I already tried this
connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
} else {
}
}
@Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
});
But I don't know how to use it, please help me.
回答1:
To achieve this, you need to create a new category in your Firebase database called onlineUsers
. Every time a user is connecting to your app, add him to this newly created category. Then you can query on that category to see the exact number of users like this:
int numberOfUsers = dataSnapshot.getChildrenCount();.
If you need to display a green dot for online members in a list of members, then the way in which you need to add these users in this new node, is to have the id as it's key and the value as a boolean. The default boolean value must be false
, which means that the user is not logged in. Your new node should look like this:
userId1: true
userId2: false
userId3: true
Every time a user signs in, change the value of that user from false
to true
. To display them, just query your database accordingly to see which users have the value of true
.
回答2:
If clients have a server to work up against,
each client connection is reported to the server, which increments a coutner.
And for such increment server is notifying (e.g. using Firebase data notification message) all clients.
This is how all clients will have indication about how many are conencted at any given time.
(When a new user is logged in, server is sending data about current number of connections)
来源:https://stackoverflow.com/questions/44882134/online-users-in-firebase-chat-app