这一节就是消息发送与接收的实现了
接收消息主要代码:
//消息监听 ChatManager cm = XmppConnection.getConnection().getChatManager(); //发送消息给pc服务器的好友(获取自己的服务器,和好友) final Chat newchat = cm.createChat(pFRIENDID, null); cm.addChatListener(new ChatManagerListener() { @Override public void chatCreated(Chat chat, boolean able) { chat.addMessageListener(new MessageListener() { @Override public void processMessage(Chat chat, Message message) { //收到来自pc服务器的消息(获取自己好友发来的信息) if(message.getFrom().contains(userChat)) { //获取用户、消息、时间、IN String[] args = new String[] {userChat, message.getBody(), TimeRender.getDate(), "IN" }; //在handler里取出来显示消息 android.os.Message msg = handler.obtainMessage(); msg.what = 1; msg.obj = args; msg.sendToTarget(); } } }); } });
//发送消息 Button btsend = (Button) findViewById(R.id.formclient_btsend); btsend.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //获取text文本 String msg = msgText.getText().toString(); if(msg.length() > 0){ //发送消息 listMsg.add(new Msg(pUSERID, msg, TimeRender.getDate(), "OUT")); //刷新适配器 adapter.notifyDataSetChanged(); try { //发送消息 newchat.sendMessage(msg); }catch (XMPPException e) { e.printStackTrace(); } } else { Toast.makeText(ChatActivity.this, "发送信息不能为空", Toast.LENGTH_SHORT).show(); } //清空text msgText.setText(""); } });
主要代码:
myMood = ((EditText)myMoodView.findViewById(R.id.myMood)).getText().toString().trim(); System.out.println("我更改的心情是:"+myMood); XmppService.changeStateMessage(connection, myMood); myStatusText.setText(myMood);
/** * 修改心情 * @param connection * @param status */ public static void changeStateMessage(final XMPPConnection connection,final String status) { Presence presence = new Presence(Presence.Type.available); presence.setStatus(status); connection.sendPacket(presence); }