android firebase 一对一聊天应用

Posted

技术标签:

【中文标题】android firebase 一对一聊天应用【英文标题】:android firebase one to one chat application 【发布时间】:2017-08-23 07:39:34 【问题描述】:

我尝试使用 mvp 开发一对一的聊天应用程序 当应用程序第一次运行时,聊天正常工作并将消息发送给用户。 问题是当我尝试使用另一个帐户注册并尝试发送消息时,firebase 创建了两个不同的聊天室,但我无法收到消息,因为第二个用户没有检测到已创建聊天室并创建了另一个 cn 你帮帮我好吗?? 这是我尝试发送消息的代码:

最终字符串 room_type_1 = chat.getSenderUid() + "_" + chat.getReceiverUid(); final String room_type_2 = chat.getReceiverUid() + "_" + chat.getSenderUid();

    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    databaseReference.child(Constants.ARG_CHAT_ROOMS).getRef().addValueEventListener(new ValueEventListener() 
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) 
            if (dataSnapshot.hasChild(room_type_1)) 
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_1 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.getTimestamp())).setValue(chat);
             else if (dataSnapshot.hasChild(room_type_2)) 
                Log.e(TAG, "sendMessageToFirebaseUser: " + room_type_2 + " exists");
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_2).child(String.valueOf(chat.getTimestamp())).setValue(chat);

             else 
                Log.e(TAG, "sendMessageToFirebaseUser: success");
                Log.e("sender uis",""+chat.getSenderUid());
                Log.e("srevier uis",""+chat.getSenderUid());
                databaseReference.child(Constants.ARG_CHAT_ROOMS).child(room_type_1).child(String.valueOf(chat.getTimestamp())).setValue(chat);
                getMessageFromFirebaseUser(chat.getSenderUid(), chat.getReceiverUid());

            

            sendPushNotificationToReceiver(chat.sender,
                    chat.message,
                    chat.senderUid,
                    new SharedPrefUtil(context).getString(Constants.ARG_FIREBASE_TOKEN),
                    receiverFirebaseToken);
            mOnSendMessageListener.onSendMessageSuccess();


        

        @Override
        public void onCancelled(DatabaseError databaseError) 
            mOnSendMessageListener.onSendMessageFailure("Unable to send message: " + databaseError.getMessage());
        
    );

这是我从 firebase 获取消息的代码

public void getMessageFromFirebaseUser(final Context context, String senderUid, String receiverUid, final ChatFragmentListener chatFragmentListener)

    final String room_type_1 = senderUid + "_" + receiverUid;
    final String room_type_2 = receiverUid + "_" + senderUid;


    final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    final DatabaseReference databaseChats = FirebaseDatabase.getInstance().getReference().child(Constants.ARG_CHAT_ROOMS);
    databaseChats.keepSynced(true);


    databaseReference.child(Constants.ARG_CHAT_ROOMS).getRef().addListenerForSingleValueEvent(new ValueEventListener() 
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) 
            if (dataSnapshot.hasChild(room_type_1)) 
                Log.e(TAG, "getMessageFromFirebaseUser: " + room_type_1 + " exists");

                FirebaseDatabase.getInstance()
                        .getReference()
                        .child(Constants.ARG_CHAT_ROOMS)
                        .child(room_type_1).addChildEventListener(new ChildEventListener() 
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) 

                        if (dataSnapshot.getKey() != s) 
                            Chat chat = new Chat();
                            chat = dataSnapshot.getValue(Chat.class);
                            chatFragmentListener.onGetMessagesSuccess(chat);

                            Log.e("1", "get");
                        


                        // do something here


                    

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) 
                             /* Log.e("childadded","eeeee"+s);
                                Log.e("chilchanged","ee"+dataSnapshot.getKey());
                                Chat chat=dataSnapshot.getValue(Chat.class);
                                String key=dataSnapshot.getKey();
                                if(!key.equals(s))chats.add(chat);*/

                    

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) 


                    

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) 
                              /* Log.e("childadded","eeeee"+s);
                                Log.e("childmoved","ee"+dataSnapshot.getKey());
                                Chat chat=dataSnapshot.getValue(Chat.class);
                                String key=dataSnapshot.getKey();
                                if(key.equals(s))chats.remove(chat);*/
                    

                    @Override
                    public void onCancelled(DatabaseError databaseError) 
                        // lll
                        chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
                    
                );

             else if (dataSnapshot.hasChild(room_type_2)) 
                Log.e(TAG, "getMessageFromFirebaseUser: " + room_type_2 + " exists");

                FirebaseDatabase.getInstance()
                        .getReference()
                        .child(Constants.ARG_CHAT_ROOMS)
                        .child(room_type_2).addChildEventListener(new ChildEventListener() 
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) 
                        Chat chat = new Chat();
                        chat = dataSnapshot.getValue(Chat.class);
                        chatFragmentListener.onGetMessagesSuccess(chat);
                        Log.e("2", "get");
                    

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) 

                    

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) 

                    

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) 

                    

                    @Override
                    public void onCancelled(DatabaseError databaseError) 
                        chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
                    
                );


             else 
                Log.e(TAG, "getMessageFromFirebaseUser: no such room available");
            
        

        @Override
        public void onCancelled(DatabaseError databaseError) 
            chatFragmentListener.onGetMessagesFailure("Unable to get message: " + databaseError.getMessage());
        
    );


.

【问题讨论】:

【参考方案1】:

这个问题最简单的解决方案是通过将用户 uuid 按升序或降序排列来创建聊天室。

public String getChatRoom(String fromUserId,String toMessageId)

           String chatRoom;

            if(fromUserId.compareTo(toMessageId) < 0 )
                // ToMessageId has less alphabetic order then fromUserId
              chatRoom =  toMessageId+" "+fromUserId;
            else
              chatRoom  = fromUserId+" "+toMessageId;
            
            return chatRoom;

Here 是 firebase 聊天应用的示例实现

【讨论】:

以上是关于android firebase 一对一聊天应用的主要内容,如果未能解决你的问题,请参考以下文章

数据库应该如何用于firebase中的一对一聊天应用程序

用于聊天应用的 Firebase 实时数据库或 Firestore? [关闭]

如何为一对一聊天应用编写 Firestore 规则?

使用 Firebase 的聊天应用程序:收到新消息时获取通知 - Android

使用 Firebase 在 android/iOS 应用程序与网络之间聊天

Android多人视频聊天应用的开发多人聊天