- 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<String, String> 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<RosterEntry> 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<Jid> addresses) {
Logger.e("entriesAdded");
}
@Override public void entriesUpdated(Collection<Jid> addresses) {
Logger.e("entriesUpdated");
}
@Override public void entriesDeleted(Collection<Jid> 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();
}
}