Android 开发即时聊天工具 YQ :(五) 发送消息
|
admin
2013年2月25日 14:24
本文热度 3919
|
服务器端转发消息功能上节已经实现,只需将消息转发给消息包中的接收人即可
- if(m.getType().equals(YQMessageType.COM_MES)){
-
- ServerConClientThread scc=ManageServerConClient.getClientThread(m.getReceiver());
- ObjectOutputStream oos=new ObjectOutputStream(scc.s.getOutputStream());
-
- oos.writeObject(m);
- }
if(m.getType().equals(YQMessageType.COM_MES)){//如果是普通消息包
//取得接收人的通信线程
ServerConClientThread scc=ManageServerConClient.getClientThread(m.getReceiver());
ObjectOutputStream oos=new ObjectOutputStream(scc.s.getOutputStream());
//向接收人发送消息
oos.writeObject(m);
}
在客户端收到消息包后,通过广播发送到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
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 chatEntity=new ArrayList();
-
- 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();
-
-
-
- }
- }
- }
public class RecentActivity extends Activity{
ListView listView;
List chatEntity=new ArrayList();
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);
}
}
}
该文章在 2013/2/25 14:24:48 编辑过