Firebase聊天应用程序中的在线用户 [英] Online users in firebase chat app

查看:90
本文介绍了Firebase聊天应用程序中的在线用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase数据库构建一个chatapp。我需要显示在线用户,我该怎么做?
我已经尝试过这个

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.

推荐答案

要实现此目的,您需要在Firebase数据库中创建一个名为 onlineUsers 的新类别。每次用户连接到您的应用程序时,请将其添加到此新创建的类别中。然后,您可以在该类别上查询以查看确切的用户数量,如下所示:

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();.

如果您需要在成员列表中为在线成员显示绿点,则输入方式您需要在这些新节点中添加这些用户的方法是将id作为键,并将值作为布尔值。默认布尔值必须为 false ,这意味着用户尚未登录。新节点应如下所示:

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

每次用户登录时,将该用户的值从 false 更改为 true 。要显示它们,只需相应地查询您的数据库,以查看哪些用户具有 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.

这篇关于Firebase聊天应用程序中的在线用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆