XMPP系列之Smack(4.1.3)(一)登錄服務器
XMPP系列之Smack(4.1.3 )(三)獲取已加入的聊天室列表
XMPP系列之Smack(4.1.3 )(四)創建聊天室
接著上一篇,要實現類似QQ好友分組的功能很簡單,從服務器讀取到好友分組以及各個分組內的成員。
首先還是要通過連接管理器單例來獲得連接類,前一章已經講解了如何配置并初始化XMPPTCPConnection
,在這里要說明一下如何創建這個單例管理類,我們通過加雙重鎖的方式來創建這個類,方法如下
public static XMPPConnectionManager getInstance() {
if (connectionManager == null) {
synchronized (XMPPConnectionManager.class) {
if (connectionManager == null) {
connectionManager = new XMPPConnectionManager();
}
}
}
return connectionManager;
}
這樣可以保證在加鎖的情況下防止對象為空。
通過管理類獲取連接對象
public XMPPTCPConnection getConnection() {
if (connection == null) {
throw new RuntimeException("請先初始化連接");
}
return connection;
}
服務器上所有的注冊用戶都通過Roster
來獲得,獲取名單對象Roster
的方法和之前有所差異,之前是通過new一個Roster
對象,現在通過一個Roster單例獲取
public static synchronized Roster getInstanceFor(XMPPConnection connection) {
Roster roster = INSTANCES.get(connection);
if (roster == null) {
roster = new Roster(connection);
INSTANCES.put(connection, roster);
}
return roster;
}
我們直接注入一個連接對象即可
Roster roster = Roster.getInstanceFor(connection);
如果有延遲還可以來一個判斷條件
if (!roster.isLoaded()) {
try {
roster.reloadAndWait();
} catch (SmackException.NotLoggedInException | SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
有了名單對象后就可以獲取所有的分組以及所有的好友了,首先獲取服務器上創建的所有分組:
Collection<RosterGroup> rosterEntries = roster.getGroups();
接下來通過遍歷來取得我們需要的Group對象
for (RosterGroup rosterGroup : rosterEntries) {
String groupName = rosterGroup.getName();
int count = rosterGroup.getEntryCount();
FriendGroup mainGroup = new FriendGroup();
mainGroup.setName(groupName);
mainGroup.setCount(String.valueOf(count));
groupList.add(mainGroup);
這里我創建了一個model(FriendGroup)來取得我所需要的組名和組內的好友數量,然后通過rosterGroup獲取到組內的好友
List<RosterEntry> rosterEntryList = rosterGroup.getEntries();
List<FriendEntity> tempChildList = new ArrayList<>();
for (int i = 0; i < rosterEntryList.size(); i++) {
RosterEntry rosterEntry = rosterEntryList.get(i);
FriendEntity mainChild = new FriendEntity();
Presence presence = roster.getPresence(rosterEntry.getUser());
Log.e("狀態", "presence=" + presence);
Log.e("狀態", "presence status=" + presence.getStatus());
Log.e("狀態", "presence mode=" + presence.getMode());
if (presence.isAvailable()) {
mainChild.setPresence("[在線]");
} else {
mainChild.setPresence("[離線]");
}
mainChild.setName(rosterEntry.getName());
mainChild.setJid(rosterEntry.getUser());
tempChildList.add(mainChild);
}
childList.add(tempChildList);
獲取好友在線狀態是通過獲取到的Presence
對象來判斷的,下面是smack源碼描述:
Paste_Image.png
到此獲取分組及好友就搞定了,如何顯示大家各顯神通吧!
下一章會講述如何獲取聊天室也就是QQ的群列表!再見!!!