Android 开发即时聊天工具 YQ :(五) 发送消息

服务器端转发消息功能上节已经实现,只需将消息转发给消息包中的接收人即可,

if(m.getType().equals(YQMessageType.COM_MES)){//如果是普通消息包  
   //取得接收人的通信线程  
   ServerConClientThread scc=ManageServerConClient.getClientThread(m.getReceiver());
   ObjectOutputStream oos=new ObjectOutputStream(scc.s.getOutputStream());  
   //向接收人发送消息  
   oos.writeObject(m);  
}
在客户端收到消息包后,通过广播发送到ChatActivity中:

//把从服务器获得的消息发送到ChatActivity
	Intent intent = new Intent("org.yhn.yq.mes");
	String[] message=new String[]{
		m.getSender()+"",
		m.getContent(),
		m.getSendTime()};
	intent.putExtra("message", message);
	context.sendBroadcast(intent);

ChatActivity:

public class RecentActivity extends Activity{
	ListView listView;
	List<RecentEntity> chatEntity=new ArrayList<RecentEntity>();
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_recent);
		 //注册广播
		IntentFilter myIntentFilter = new IntentFilter(); 
        myIntentFilter.addAction("org.yhn.yq.mes");
        registerReceiver(new MyBroadcastReceiver(), myIntentFilter);
	}

	
	public class MyBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String[] mes = intent.getStringArrayExtra("message");
		    Toast.makeText(context, "收到["+mes[0]+"]的消息:"+mes[1], Toast.LENGTH_SHORT).show();
		    //更新最近会话列表

		    //unregisterReceiver(MyBroadcastreceiver);
		}
	}
}




源码已经上传至我的资源,谢谢大家支持!欢迎一起学习交流!

转载请注明出处:http://blog.csdn.net/mimitracely


你可能感兴趣的:(android,ListView,String,服务器,聊天,工具)