在前面两篇文章Android基于XMPP Smack及Openfire学习笔记(1)及Android基于XMPP Smack及Openfire学习笔记(2)中,分别讲了用户注册,登录,修改密码等。代码凌乱,所以参考网上资料,就写了个工具类。方便以后直接使用。继续学习中…..
/** * Android XMPP Openfire操作工具类 * 注册,登录,修改密码及更改用户在线状态,可以直接调用对应方法 * 比如注册就调用:XMPPConnectTool.getInstance().registerToServer(); * @description: * @date 2016-2-20 下午2:43:29 */
public class XMPPConnectTool {
private static final String HOST_IP = "127.0.0.1";// 服务器ip
private static final int PORT = 5222;
private static final String SERVER_NAME = "hxxxx";// 服务器名称,完成openfire安装 ,后台 可以查看到
private static XMPPConnectTool instance;
private XMPPConnection mXmppConnection = null;
private XMPPConnectTool() {
}
// 单例模式
public static XMPPConnectTool getInstance() {
if (instance == null) {
instance = new XMPPConnectTool();
}
return instance;
}
// 获取XMPPConnection对象
public XMPPConnection getConnection() {
if (mXmppConnection == null) {
initConnection();
}
return mXmppConnection;
}
/** * 初始化建立链接 * @description: * @author ldm * @date 2016-2-20 下午2:53:50 */
public boolean initConnection() {
try {
if (null == mXmppConnection || !mXmppConnection.isAuthenticated()) {
// 配置ConnectionConfiguration
ConnectionConfiguration config = new ConnectionConfiguration(HOST_IP, PORT, SERVER_NAME);
// 设置可以重连
config.setReconnectionAllowed(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
// 设离线,可以取离线消息
config.setSendPresence(true);
// 是否启用安全验证
config.setSASLAuthenticationEnabled(false);
config.setTruststorePath("/system/etc/security/cacerts.bks");
config.setTruststorePassword("changeit");
config.setTruststoreType("bks");
mXmppConnection = new XMPPConnection(config);
// 连接到服务器
mXmppConnection.connect();
// 配置各种Provider,如果不配置,则会无法解析数据
configureProviderManager(ProviderManager.getInstance());
return true;
}
}
catch (XMPPException e) {
mXmppConnection = null;
e.printStackTrace();
}
return false;
}
/** * 配置ProviderManager * 这些也是网上找的,很多都还不知道是啥东东,慢慢学习 * @description: * @author ldm * @date 2016-2-20 下午3:15:17 */
public void configureProviderManager(ProviderManager pm) {
// Private Data Storage
pm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());
// Time
try {
pm.addIQProvider("query", "jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
}
catch (ClassNotFoundException e) {
Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time");
}
// Roster Exchange
pm.addExtensionProvider("x", "jabber:x:roster", new RosterExchangeProvider());
// Message Events
pm.addExtensionProvider("x", "jabber:x:event", new MessageEventProvider());
// Chat State
pm.addExtensionProvider("active", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("composing", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("paused", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("inactive", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
pm.addExtensionProvider("gone", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
// XHTML
pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());
// Group Chat Invitations
pm.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());
// Service Discovery # Items
pm.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
// Service Discovery # Info
pm.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
// Data Forms
pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
// MUC User
pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());
// MUC Admin
pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
// MUC Owner
pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
// Delayed Delivery
pm.addExtensionProvider("x", "jabber:x:delay", new DelayInformationProvider());
// Version
try {
pm.addIQProvider("query", "jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
// VCard
pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
// Offline Message Requests
pm.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
// Offline Message Indicator
pm.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
// Last Activity
pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());
// User Search
pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());
// SharedGroupsInfo
pm.addIQProvider("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());
// JEP-33: Extended Stanza Addressing
pm.addExtensionProvider("addresses", "http://jabber.org/protocol/address", new MultipleAddressesProvider());
// FileTransfer
pm.addIQProvider("si", "http://jabber.org/protocol/si", new StreamInitiationProvider());
pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
// Privacy
pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError());
pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError());
pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError());
pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError());
pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError());
}
/** * 断开连接 * @description: * @author ldm * @date 2016-2-20 下午3:18:33 */
public void closeXmpp() {
if (mXmppConnection != null) {
// 启用disconnect();
if (mXmppConnection.isConnected()) mXmppConnection.disconnect();
mXmppConnection = null;
}
}
/** * 登录操作 * @description: * @author ldm * @date 2016-2-20 下午3:19:41 */
public void loginToServer(String name, String pwd) {
try {
if (getConnection() == null) return;
// 进行登录操作:传入用户名,密码
getConnection().login(name, pwd);
// 登录成功更改在线状态
Presence presence = new Presence(Presence.Type.available);
getConnection().sendPacket(presence);
}
catch (XMPPException xe) {
xe.printStackTrace();
}
}
/** * 注册 * 注册返回说明: * 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败 * @description: * @date 2016-2-20 下午3:24:08 */
public String registerToServer(String name, String pwd) {
if (getConnection() == null) return "0";
Registration reg = new Registration();
reg.setUsername(name);
reg.setPassword(pwd);
reg.setType(IQ.Type.SET);
reg.setTo(getConnection().getServiceName());
// 这边addAttribute不能为空,否则出错
reg.addAttribute("android", "geolo_createUser_android");
PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
PacketCollector collector = getConnection().createPacketCollector(filter);
getConnection().sendPacket(reg);
IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (result == null) {
return "0";
}
else if (result.getType() == IQ.Type.RESULT) {
return "1";
}
else {
if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
return "2";
}
else {
return "3";
}
}
}
/** * 用户登录 成功后,设置用户在线状态 * @description: * @date 2016-2-20 下午3:26:27 */
public void setUserState(int code) {
XMPPConnection con = getConnection();
if (con == null) return;
Presence presence = null;
switch (code) {
case 0:
presence = new Presence(Presence.Type.available);// 设置在线
con.sendPacket(presence);
break;
case 1:
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.chat);// 设置Q我吧
con.sendPacket(presence);
break;
case 2:
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.dnd);// 设置忙碌
con.sendPacket(presence);
break;
case 3:
presence = new Presence(Presence.Type.available);
presence.setMode(Presence.Mode.away);// 设置离开"
con.sendPacket(presence);
break;
case 4:
Roster roster = con.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
presence = new Presence(Presence.Type.unavailable);
presence.setPacketID(Packet.ID_NOT_AVAILABLE);
presence.setFrom(con.getUser());
presence.setTo(entry.getUser());
con.sendPacket(presence);
Log.v("state", presence.toXML());
}
// 向同一用户的其他客户端发送隐身状态
presence = new Presence(Presence.Type.unavailable);
presence.setPacketID(Packet.ID_NOT_AVAILABLE);
presence.setFrom(con.getUser());
presence.setTo(StringUtils.parseBareAddress(con.getUser()));
con.sendPacket(presence);
break;
case 5:
presence = new Presence(Presence.Type.unavailable);
con.sendPacket(presence);// 设置离线
break;
default:
break;
}
}
/** * 修改密码 * @description: * @date 2016-2-20 下午3:29:19 */
public boolean changePwd(String pwd) {
if (getConnection() == null) return false;
try {
getConnection().getAccountManager().changePassword(pwd);
return true;
}
catch (XMPPException e) {
return false;
}
}
}