本文主要是介绍Android基于XMPP Smack及Openfire学习笔记(3),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在前面两篇文章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";// 服务器ipprivate 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()) {// 配置ConnectionConfigurationConnectionConfiguration 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 Storagepm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());// Timetry {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 Exchangepm.addExtensionProvider("x", "jabber:x:roster", new RosterExchangeProvider());// Message Eventspm.addExtensionProvider("x", "jabber:x:event", new MessageEventProvider());// Chat Statepm.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());// XHTMLpm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());// Group Chat Invitationspm.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());// Service Discovery # Itemspm.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());// Service Discovery # Infopm.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());// Data Formspm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());// MUC Userpm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());// MUC Adminpm.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());// MUC Ownerpm.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());// Delayed Deliverypm.addExtensionProvider("x", "jabber:x:delay", new DelayInformationProvider());// Versiontry {pm.addIQProvider("query", "jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));}catch (ClassNotFoundException e) {e.printStackTrace();}// VCardpm.addIQProvider("vCard", "vcard-temp", new VCardProvider());// Offline Message Requestspm.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());// Offline Message Indicatorpm.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());// Last Activitypm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());// User Searchpm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());// SharedGroupsInfopm.addIQProvider("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());// JEP-33: Extended Stanza Addressingpm.addExtensionProvider("addresses", "http://jabber.org/protocol/address", new MultipleAddressesProvider());// FileTransferpm.addIQProvider("si", "http://jabber.org/protocol/si", new StreamInitiationProvider());pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());// Privacypm.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;}}}
这篇关于Android基于XMPP Smack及Openfire学习笔记(3)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!