Android 开发即时聊天工具 YQ :(五) 发送消息
服务器端转发消息功能上节已经实现,只需将消息转发给消息包中的接收人即可,
1 if(m.getType().equals(YQMessageType.COM_MES)){//如果是普通消息包 2 //取得接收人的通信线程 3 ServerConClientThread scc=ManageServerConClient.getClientThread(m.getReceiver()); 4 ObjectOutputStream oos=new ObjectOutputStream(scc.s.getOutputStream()); 5 //向接收人发送消息 6 oos.writeObject(m); 7 }
在客户端收到消息包后,通过广播发送到ChatActivity中:
1 //把从服务器获得的消息发送到ChatActivity 2 Intent intent = new Intent("org.yhn.yq.mes"); 3 String[] message=new String[]{ 4 m.getSender()+"", 5 m.getContent(), 6 m.getSendTime()}; 7 intent.putExtra("message", message); 8 context.sendBroadcast(intent);
ChatActivity:
1 public class RecentActivity extends Activity{ 2 ListView listView; 3 List<RecentEntity> chatEntity=new ArrayList<RecentEntity>(); 4 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 requestWindowFeature(Window.FEATURE_NO_TITLE); 8 setContentView(R.layout.activity_recent); 9 //注册广播 10 IntentFilter myIntentFilter = new IntentFilter(); 11 myIntentFilter.addAction("org.yhn.yq.mes"); 12 registerReceiver(new MyBroadcastReceiver(), myIntentFilter); 13 } 14 15 16 public class MyBroadcastReceiver extends BroadcastReceiver { 17 @Override 18 public void onReceive(Context context, Intent intent) { 19 String[] mes = intent.getStringArrayExtra("message"); 20 Toast.makeText(context, "收到["+mes[0]+"]的消息:"+mes[1], Toast.LENGTH_SHORT).show(); 21 //更新最近会话列表 22 23 //unregisterReceiver(MyBroadcastreceiver); 24 } 25 } 26 }
谢谢大家支持!欢迎一起学习交流!