1、初始化
class Thread1 extends Thread {
@Override
public void run() {
Login(Content.DaTingSERVICE_URL, 5222, uid, "111111", uid + "@"
+ Content.DaTingSERVICE_Name);
}
}
2、登陆
public void Login(final String ServerIP, final int serverport,
final String Username, final String Password, String userid) {
connConfig = new ConnectionConfiguration(ServerIP, serverport,Content.DaTingSERVICE_Name);
connConfig.setReconnectionAllowed(true);
connConfig.setSASLAuthenticationEnabled(false);
connConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
xmppConnection = new XMPPConnection(connConfig);
new Thread() {
@Override
public void run() {
try {
xmppConnection.connect();
xmppConnection.login(Username, Password);
JoinRoom(Content.DaTingSERVICE_Home + "@conference."
+ Content.DaTingSERVICE_Name);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}.start();
}
3、加入房间
public void JoinRoom(String jid) {
MultiUserChat multiUserChat = new MultiUserChat(xmppConnection, jid);
curmultchat = multiUserChat;
if (curmultchat != null) {
try {
DiscussionHistory history = new DiscussionHistory();
history.setSince(new Date(lastLoginTime==0 ? lastLoginTime:lastLoginTime-172800000));
multiUserChat.join(User, "111111", history,SmackConfiguration.getPacketReplyTimeout());
RegisterRoomMessageListener();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
4、注册房间监听
public void RegisterRoomMessageListener() {
curroomListener = new PacketListener() {
public void processPacket(Packet arg0) {
Message message = (Message) arg0;
String msg = message.getBody();
String fromString = message.getFrom();
fromString = fromString.substring(fromString.indexOf('/') + 1);
entity = new ChatMsgEntity();
DelayInformation inf = (DelayInformation) message.getExtension(
"x", "jabber:x:delay");
if (inf != null) {
entity.setDate(inf.getStamp());
} else {
entity.setDate(new Date());
}
entity.setName(fromString);
entity.setText(msg.toString());
mDataArrays.add(entity);
mAdapter.notifyDataSetChanged();
mListView.setSelection(mListView.getCount() - 1);
handler.sendEmptyMessage(1);
}
};
curmultchat.addMessageListener(curroomListener);
}
5、退出一个房间
public void QuitRoomChat() {
if (curmultchat != null && xmppConnection != null
&& xmppConnection.isConnected()) {
curmultchat.leave();
a = System.currentTimeMillis();
curmultchat.removeMessageListener(curroomListener);
}
}
6、关闭连接
public void closeConnection() {
if (xmppConnection != null) {
if (xmppConnection.isConnected())
xmppConnection.disconnect();
xmppConnection = null;
}
}
可参考:http://blog.csdn.net/shimiso/article/details/8816540