Android Studio依赖或者官网下载
// XMPP通信
compile 'org.igniterealtime.smack:smack-im:4.2.0'
compile 'org.igniterealtime.smack:smack-tcp:4.2.0'
compile "org.igniterealtime.smack:smack-android-extensions:4.2.0"
compile "org.igniterealtime.smack:smack-android:4.2.0"
服务器连接
/**
* 连接服务器
* @return 连接服务器对象
*/
public void connect() {
try {
XMPPTCPConnectionConfiguration configuration =
XMPPTCPConnectionConfiguration.builder().setXmppDomain(XMPP_DOMAIN) // 设置域名
.setHostAddress(InetAddress.getByName(XMPP_HOST)) // 设置主机
.setPort(5222) // 设置端口
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) // 禁用SSL连接
.setCompressionEnabled(false) // 禁用SSL连接
//.setSendPresence(false) // 设置为离线状态
.setDebuggerEnabled(true) // 开启调试模式
.build();
// 设置需要经过同意才可以添加好友
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
AbstractXMPPConnection connection = new XMPPTCPConnection(configuration);
connection.connect();// 连接, 可设置监听
connection.addConnectionListener(new XMPPConnectionListener());
this.mConnection = connection;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (XmppStringprepException e) {
e.printStackTrace();
} catch (InterruptedException | IOException | XMPPException | SmackException e) {
e.printStackTrace();
}
}
其中XMPPConnectionListener类实际上是实现ConnectionListener接口。
/**
* 服务器连接监听
* Created by mazaiting on 2017/9/19.
*/
public class XMPPConnectionListener implements ConnectionListener {
@Override public void connected(XMPPConnection connection) {}
@Override public void authenticated(XMPPConnection connection, boolean resumed) {}
@Override public void connectionClosed() {}
@Override public void connectionClosedOnError(Exception e) {}
@Override public void reconnectionSuccessful() {}
@Override public void reconnectingIn(int seconds) {}
@Override public void reconnectionFailed(Exception e) {}
}
关闭连接则使用
/**
* 关闭连接
*/
public void disConnect() {
checkConnect();
if (mConnection.isConnected()) mConnection.disconnect();
mConnection = null;
}
登录
/**
* 登录服务器
* @param userName 用户名
* @param passWord 密码
* @return 是否登录成功。 true 成功; false 失败。
*/
public boolean login(String userName, String passWord) {
checkConnect(); // 检查是否连接
try {
if (!mConnection.isAuthenticated()){ // 判断是否登录
mConnection.login(userName, passWord);
addListener(); // 设置一些监听
return true;
}
return false;
} catch (XMPPException | SmackException | InterruptedException | IOException e) {
Logger.e("登录出错");
e.printStackTrace();
return false;
}
}
注册
在注册时非安全链接,无法注册的情况,采取smack.jar内部代码,越过非安全链接的判断。
/**
* 创建用户
* @param userName 用户名
* @param passWord 密码
* @param attributes 属性
*/
public void createAccount(String userName, String passWord, Map attributes)
throws SmackException.NotConnectedException, InterruptedException,
XMPPException.XMPPErrorException, SmackException.NoResponseException {
if (StringUtils.isNullOrEmpty(userName)) {
throw new IllegalArgumentException("Username must not be null");
}
if (StringUtils.isNullOrEmpty(passWord)) {
throw new IllegalArgumentException("Password must not be null");
}
attributes.put("username", userName); // 设置用户名
attributes.put("password", passWord); // 设置密码
Registration reg = new Registration(attributes);
reg.setType(IQ.Type.set); // 设置类型
reg.setTo(mConnection.getXMPPServiceDomain());// 设置发送地址
createStanzaCollectorAndSend(reg).nextResultOrThrow();
}
private StanzaCollector createStanzaCollectorAndSend(IQ req) throws
SmackException.NotConnectedException, InterruptedException {
StanzaCollector collector = mConnection.createStanzaCollectorAndSend(new StanzaIdFilter(req.getStanzaId()), req);
return collector;
}
获取当前用户
/**
* 获取当前用户
*/
public EntityFullJid getCurrentUser() {
return mConnection.getUser();
}
获取好友列表
/***
* 获取好友列表
*/
public void getFriendList() {
checkConnect();
Roster roster = Roster.getInstanceFor(mConnection);
Set entries = roster.getEntries();
Logger.e(entries.size() + "");
for (RosterEntry entry : entries) {
Logger.e(entry.toString());
}
}
添加角色监听
/**
* 添加关于角色的监听
*/
private void addRosterListener() {
// 获取当前角色
Roster roster = Roster.getInstanceFor(mConnection);
// 接收到好友信息变化
mReceiverFriendStatusListener = new ReceiverFriendStatusListener();
roster.addRosterListener(mReceiverFriendStatusListener);
// 接收到添加好友信息
mAddFriendMessageListener = new AddFriendMessageListener();
roster.addSubscribeListener(mAddFriendMessageListener);
}
/**
* 获取到其他人添加自己的信息监听
* Created by mazaiting on 2017/9/19.
*/
public class AddFriendMessageListener implements SubscribeListener {
@Override public SubscribeAnswer processSubscribe(Jid from, Presence subscribeRequest) {
// TODO添加好友请求
Logger.e("processSubscribe");
return null;
}
}
/**
* 可以接收到其他人是否删除了自己,好友在线状态改变
* Created by mazaiting on 2017/9/19.
*/
public class ReceiverFriendStatusListener implements RosterListener {
@Override public void entriesAdded(Collection addresses) {
Logger.e("entriesAdded");
}
@Override public void entriesUpdated(Collection addresses) {
Logger.e("entriesUpdated");
}
@Override public void entriesDeleted(Collection addresses) {
Logger.e("entriesDeleted");
}
@Override public void presenceChanged(Presence presence) {
Logger.e("presenceChanged");
}
}
设置当前用户状态
/**
* 设置在线、离线等状态
*/
public void setOnLine(Presence.Type type) {
try {
checkConnect();
if (isOnLine != type) {
Presence presence = new Presence(type);
//presence.setStatus("Gone fishing");// 设置状态消息
mConnection.sendStanza(presence);
isOnLine = type;
}
} catch (Exception e) {
e.printStackTrace();
}
}