Implementing Message Sending for Android Instant Messaging App YQ
On the server side, message forwarding functionality is already implemented from prior work. The server only needs to route incoming messages to the inetnded recipient specified in the message envelope:
if (message.getType().equals(MessageType.COMMON_MESSAGE)) {
// Get the active connection thread for the receiving user
ClientConnectionThread targetClient = ConnectionManager.getClientThread(message.getReceiver());
ObjectOutputStream objectOut = new ObjectOutputStream(targetClient.getSocket().getOutputStream());
// Transmit the full message object to the recipient
objectOut.writeObject(message);
}
After the client reecives the message packet from the server, it broadcasts the message data to the chat UI activity:
// Broadcast incoming message content to the chat activity
Intent broadcastIntent = new Intent("com.example.im.message_received");
String[] messageData = new String[]{
incomingMessage.getSender(),
incomingMessage.getContent(),
incomingMessage.getSendTimestamp()
};
broadcastIntent.putExtra("incoming_message", messageData);
context.sendBroadcast(broadcastIntent);
The conversation list activity registers a broadcast receiver to process incoming messages:
public class ConversationListActivity extends Activity {
ListView conversationListView;
List<RecentConversation> recentConversations = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_conversation_list);
// Register broadcast receiver for new incoming messages
IntentFilter messageFilter = new IntentFilter();
messageFilter.addAction("com.example.im.message_received");
registerReceiver(new IncomingMessageReceiver(), messageFilter);
}
public class IncomingMessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String[] messageInfo = intent.getStringArrayExtra("incoming_message");
String sender = messageInfo[0];
String content = messageInfo[1];
Toast.makeText(context, "New message from [" + sender + "]: " + content, Toast.LENGTH_SHORT).show();
// Update the recent conversation list with the new message
}
}
}