技术开发 频道

IM读取联系人


【IT168技术文档】

  最近在做IM读取联系人的工作,主要包括MSN和Gtalk,研究了以下smack和jml的文档,发现还是比较容易的,虽然代码很少,但是却颇费了一般周折
  代码如下:
package com.ruby.service.contacts; import java.util.ArrayList; import java.util.List; import net.sf.jml.MsnContact; import net.sf.jml.MsnList; import net.sf.jml.MsnMessenger; import net.sf.jml.MsnUserStatus; import net.sf.jml.event.MsnContactListAdapter; import net.sf.jml.impl.MsnMessengerFactory; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; public class IMRosterService { private String user; private String password; private String type; public IMRosterService(String user, String password, String type) { this.user = user; this.password = password; this.type = type; } public List<ContactFriend> getContactList() { if(type.equals("msn")) return getMsnRoster(); return getGtalkRoster(); } private List<ContactFriend> getMsnRoster() { MsnMessenger messenger = null; final List<ContactFriend> list = new ArrayList<ContactFriend>(); try { messenger = MsnMessengerFactory.createMsnMessenger(user, password); messenger.getOwner().setInitStatus(MsnUserStatus.BUSY); messenger.addContactListListener(new MsnContactListAdapter() { public void contactListInitCompleted(MsnMessenger messenger) { MsnContact[] contacts = messenger.getContactList().getContactsInList(MsnList.AL); for (int i = 0; i != contacts.length; i++) { String email = contacts[i].getEmail().getEmailAddress(); String name = contacts[i].getDisplayName(); list.add(new ContactFriend(email, name)); } } }); messenger.login(); // must wait until result Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } finally { messenger.logout(); } return list; } private List<ContactFriend> getGtalkRoster() { List<ContactFriend> list = new ArrayList<ContactFriend>(); ConnectionConfiguration connectionConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com"); XMPPConnection connection = new XMPPConnection(connectionConfig); try { connection.connect(); connection.login(user, password); Roster roster = connection.getRoster(); if(roster != null) { for (RosterEntry entry : roster.getEntries()) { String email = entry.getUser(); String name = entry.getName(); if(name==null) { name = email; } ContactFriend friend = new ContactFriend(email, name); list.add(friend); } } } catch (XMPPException e) { e.printStackTrace(); } finally { if(connection.isConnected()) connection.disconnect(); } return list; } }
0
相关文章