如何在android java中使用recyclerview实时接收聊天消息 [英] How to receive the chat message in real time using the recyclerview in android java

查看:30
本文介绍了如何在android java中使用recyclerview实时接收聊天消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 recyclerview 实现了聊天视图列表.但是列表没有实时向接收者显示消息.

I have implemented chat view list using the recyclerview. But the list not showing the message to the receiver in real time.

如果我发送消息,接收方需要实时接收消息.我怎样才能让它发挥作用.

If I send a message, the receiver needs to receive the message in real time. How can I make this to work.

我不知道 BroadCastReceiver.在这里,我正在使用聊天屏幕.需要在我的应用中显示聊天消息.

I don't have an idea about the broadCastReceiver. Here I am working with the chat screen. Need to show the chat message in my app.

问题是,如果用户向我发送消息,我无法看到该消息.我需要通过 recyclerview 接收消息.

Issue is if a user sends me a message, I can't able to see the message. I need to receive the message via the recyclerview.

在我的聊天片段中:

  private RecyclerView mChatMessageRecyclerView;
    
     @Override
        public void onResume() {
            super.onResume();
            IntentFilter filter = new IntentFilter("Message_send");
            registerForContextMenu(mChatMessageRecyclerView);
        }
    
        @Override
        public void onPause() {
            super.onPause();
            unregisterForContextMenu(mChatMessageRecyclerView);
        }
    
        private final BroadcastReceiver mReceiverRecyclerview = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                mAdapter.notifyDataSetChanged();
                mAdapter.notifyItemInserted(getItemCount() + 1);
                mChatMessageRecyclerView.smoothScrollToPosition(getItemCount() + 1);
            }
        };
    
     LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            
     @Override
        public void onViewCreated(View v, @Nullable Bundle b) {
            super.onViewCreated(v, b);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            linearLayoutManager.setStackFromEnd(true);
            linearLayoutManager.setSmoothScrollbarEnabled(true);
            linearLayoutManager.setReverseLayout(false);
         mChatMessageRecyclerView.setLayoutManager(linearLayoutManager);
            LocalBroadcastReceiver br = new LocalBroadcastReceiver() {
                @Override
                public void onReceiveIntent(@NonNull Context context, @NonNull Intent intent) {
                    mAdapter.notifyDataSetChanged();
                }
            };
            mChatMessageRecyclerView.getLayoutManager().smoothScrollToPosition(mChatMessageRecyclerView, new RecyclerView.State(), mChatMessageRecyclerView.getAdapter().getItemCount());
            
            int newMsgPosition = mAdapter.getItemCount();
            mChatMessageRecyclerView.setHasFixedSize(true);
            mChatMessageRecyclerView.setAdapter(mAdapter);
    }
    
     mSendMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String msgContent = mSendMsgInputBox.getText().toString();
    
                    if(!TextUtils.isEmpty(msgContent))
                    {
                        execute(new PostMessageRequest(message, Chatmessage.getmId(),

mPostMessageListener);
                    mSendMsgInputBox.setText("");
                }
            }
        });

我的适配器:

       private static final int VIEW_TYPE_MESSAGE_SENT = 1;
        private static final int VIEW_TYPE_MESSAGE_RECEIVED = 2;
        private List<MyMessageModel> msgDtoList; 
        MyMessageModel msgDto = this.msgDtoList.get(position);


         @Override
    public int getItemViewType(int position) {
        MyMessageModel message = (MyMessageModel) msgDtoList.get(position);

        if (message.getId().equals(Profile.getId())) {
            // If the current user is the sender of the message
            return VIEW_TYPE_MESSAGE_SENT;
        } else {
            // If some other user sent the message
            return VIEW_TYPE_MESSAGE_RECEIVED;
        }
    }

 @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;

        if (viewType == VIEW_TYPE_MESSAGE_SENT) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.sender_message_layout, parent, false);
            return new SenderMessageHolder(view);

        } else if (viewType == VIEW_TYPE_MESSAGE_RECEIVED) {
            view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.receiver_message_layout, parent, false);
            return new ReceiverMessageHolder(view);
        }
    return null;
    }
             public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                LastMessageContent message = (LastMessageContent) msgDtoList.get(position);

                switch (holder.getItemViewType()) {
                    case VIEW_TYPE_MESSAGE_SENT:
                        populateSentViewHolder(holder, position);   break;
                    case VIEW_TYPE_MESSAGE_RECEIVED:
                        populateReceivedViewHolder(holder, position);

                }

 @SuppressLint("ResourceAsColor")
    private void populateSentViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyMessageModal msgDto = this.msgDtoList.get(position);
        ((SenderMessageHolder) holder).rightMsgTextView.setText(msgDto.getmMSg());
}

 @SuppressLint("ResourceAsColor")
    private void populateReceivedViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyMessageModal msgDto = this.msgDtoList.get(position);
        ((ReceiverMessageHolder) holder).leftMsgTextView.setText(msgDto.getmMSg());
}

推荐答案

为了在您的 RecycleView 上显示实时数据,您需要实现两件事:

In order to display real-time data on your RecycleView, there are two things you need to implement:

  1. 您监听实时数据的数据源.这可能是来自例如WebSocketsFirebase、一些消息队列等
  2. 然后您需要将传入消息通知您的适配器然后更新您的 RecycleView.您希望在每次收到消息时仅使用新消息而不是整个列表来更新 RecycleView.为了您将使用 ListAdaptorDiffUtil.ItemCallback.这是一个很好的教程,解释了如何管理 RecycleView 更新(用 Kotlin 解释):https://developer.android.com/codelabs/kotlin-android-training-diffutil-databinding/#0
  1. Your data source which listens to the real time data. This could be coming from e.g. WebSockets, Firebase, some message queue, etc.
  2. Then you need to notify your adaptor about the incoming messages which then updates your RecycleView. You would like to update the RecycleView on only with the new messages and not the entire list each time a message is received. For that you would use the ListAdaptor and DiffUtil.ItemCallback. Here is a nice tutorial explaining how to manage RecycleView updates (explained with Kotlin): https://developer.android.com/codelabs/kotlin-android-training-diffutil-databinding/#0

这篇关于如何在android java中使用recyclerview实时接收聊天消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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