xmppconnection类建议使用单例实现:
public class XmppConnection{
public static int SERVER_PORT = 5222;//服务端口 可以在openfire上设置
// public static String SERVER_HOST = "192.168.0.188";//你openfire服务器所在的ip
public static String SERVER_NAME = "aaa";//设置openfire时的服务器名
public static final String XMPP_UP_MESSAGE_ACTION = "com.tarena.xmpp.chat.up.message.action";
private static XMPPConnection connection = null;
public static MessageInterceptor mMessageInterceptor = new MessageInterceptor();
public static MessageListener mMessageListener= new MessageListener();
public static ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void reconnectionSuccessful() {
Presence presence = new Presence(Presence.Type.available); //设置为登录状态
XmppConnection.getConnection().sendPacket(presence);
System.out.println("openfire重连成功");
}
@Override
public void reconnectionFailed(Exception arg0) {
System.out.println("openfire重连失败");
}
@Override
public void reconnectingIn(int arg0) {
System.out.println("openfire重连ing :"+arg0);
}
@Override
public void connectionClosedOnError(Exception arg0) { //重复登录了
if(arg0.getMessage().contains("conflict")){
System.out.println("openfire重复登录了 :"+arg0);
}
}
@Override
public void connectionClosed() {
System.out.println("openfire连接关闭");
}
};
// 断线重连,后面自己写了个重连的,这个是自带的重连,太耗电了,并且有时候不管用
static{
try{
Class.forName("org.jivesoftware.smack.ReconnectionManager");
}catch(Exception e){
e.printStackTrace();
}
}
private static synchronized void openConnection() {
XMPPConnection.DEBUG_ENABLED = true;// 开启DEBUG模式
// 配置连接
ConnectionConfiguration config = new ConnectionConfiguration(
SERVER_HOST, SERVER_PORT, SERVER_NAME);
config.setSendPresence(false); //不马上上线
config.setRosterLoadedAtLogin(false); //读取花名册
config.setReconnectionAllowed(true); //重连
config.setSecurityMode(SecurityMode.disabled); //安全连接
config.setSASLAuthenticationEnabled(false);
config.setCompressionEnabled(true); //压缩
connection = new XMPPConnection(config);
connected();// 连接到服务器
//配置各种Provider,如果不配置,则会无法解析数据
configureConnection(ProviderManager.getInstance());
}
/**
* 创建连接
*/
public static synchronized XMPPConnection getConnection() {
if (connection == null) {
openConnection();
}
return connection;
}
public static boolean isNull(){
boolean isNull = false;
if (connection == null) {
isNull = true;
}
return isNull;
}
/**
* 关闭连接
*/
public static void closeConnection() {
if(connection!=null){
XmppService.setIsLogin(false);
connection.disconnect();
connection = null;
}
}
public static boolean isConnected() {
boolean isConnected = false;
if (connection !=null && connection.isConnected()) {
isConnected = true;
}
return isConnected;
}
public static boolean isAuthenticated() {
boolean isAuthenticated = false;
if (connection !=null && connection.isAuthenticated()) {
isAuthenticated = true;
}
return isAuthenticated;
}
/**
* 手动重连,设了个service执行isBackground为true, 当点开聊天页的时候try重连一下isBackground为false
*/
public static synchronized void reConnected(boolean isBackground){
boolean canRe = false;
if(isBackground && connection != null && (!isConnected()||!isAuthenticated())){ //后台运行监测,必须不为null才重连
canRe = true;
System.out.println("openfire back 手动重连");
}else if(!isBackground && (!isConnected()||!isAuthenticated())){ //前台监测,没连接就重连
canRe = true;
System.out.println("openfire front 手动重连");
}
if (canRe) {
new Thread() {
@Override
public void run() {
if(!isConnected()){
boolean isSuccess = true;
try {
System.out.println("openfire try重连接");
connection.connect();// 消息进入拦截
connection.removePacketInterceptor(mMessageInterceptor);
connection.removePacketListener(mMessageListener);
connection.addPacketInterceptor(mMessageInterceptor,
new PacketTypeFilter(Message.class));
connection.addPacketListener(mMessageListener,
new PacketTypeFilter(Message.class));
} catch (XMPPException xe) {
isSuccess = false;
System.out.println("openfire 重连接失败");
} catch(Exception e){
e.printStackTrace();
}finally {
if (isSuccess && isConnected()) { //连接成功就登陆,自己规则自己写
addConnectListener();
autoLogin();
}
}
}
super.run();
}
}.start();
}
}
public static synchronized void connected(){
System.out.println("openfire 创造");
if(!isConnected()){
boolean isSuccess = true;
try {
connection.connect();
// 消息进入拦截
connection.addPacketInterceptor(
mMessageInterceptor, new PacketTypeFilter(Message.class));
connection.addPacketListener(mMessageListener,
new PacketTypeFilter(Message.class));
} catch (XMPPException xe) {
isSuccess = false;
System.out.println("openfire 连接失败");
xe.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}finally{
if(isSuccess && isConnected()){
addConnectListener();
autoLogin();
}
}
}
}
public static void addConnectListener(){
if(connection!=null && connectionListener!=null){
connection.removeConnectionListener(connectionListener);
connection.addConnectionListener(connectionListener);
}
}
public static synchronized void autoLogin(){
if (!isAuthenticated() && !XmppService.isLogin()) { //没登陆,登陆
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ContextUtil.getInstance());
if (sharedPreferences.getBoolean("islogined", false)) {
String name = sharedPreferences.getString("username", null);
String pwd = sharedPreferences.getString("userpwd", null);
XmppService.login(name, pwd);
}
}
}
/**
* xmpp配置
*/
private static void configureConnection(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 (Exception e) {
e.printStackTrace();
}
// 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) {
// Not sure what's happening here.
}
// 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());
pm.addIQProvider("si", "http://jabber.org/protocol/si",new StreamInitiationProvider());
pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams",new BytestreamsProvider());
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());
}
}
以下是封装了一下asmack常用方法的类Xmppservice, 另外加入一个isLogin的属性,因为xmppconnection自带的isAuthenticated()不管用,断开连接时跟isconncted()一起变成false 不是应该登陆了就一直是true的吗?难道我理解有错?
public class XmppService{
private static boolean isLogin = false;
public static IQ regist(String accounts,String password,String email,String nicheng){
Registration reg = new Registration();
reg.setType(IQ.Type.SET);
reg.setTo(XmppConnection.getConnection().getServiceName());
reg.setUsername(accounts);
reg.setPassword(password);
reg.addAttribute("name", nicheng);
reg.addAttribute("email", email);
PacketFilter filter = new AndFilter(new PacketIDFilter(
reg.getPacketID()), new PacketTypeFilter(
IQ.class));
PacketCollector collector = XmppConnection.getConnection().
createPacketCollector(filter);
XmppConnection.getConnection().sendPacket(reg);
IQ result = (IQ) collector.nextResult(SmackConfiguration
.getPacketReplyTimeout());
// Stop queuing results
collector.cancel();// 停止请求results(是否成功的结果)
return result;
}
public static synchronized boolean login(String accounts,String password){
try {
if(XmppConnection.isConnected()&& !XmppService.isLogin()){
System.out.println("openfire login");
XmppConnection.getConnection().login(accounts, password);
Presence presence = new Presence(Presence.Type.available); //设置为登录状态
XmppConnection.getConnection().sendPacket(presence);
System.out.println("openfire登陆成功");
isLogin = true;
return true;
}else{
return false;
}
} catch (XMPPException xe) {
System.out.println("openfire登陆失败");
xe.printStackTrace();
return false;
} catch (Exception e) {
System.out.println("openfire登陆失败");
e.printStackTrace();
return false;
}
}
public static boolean changPwd(String pwd){
try {
XmppConnection.getConnection().getAccountManager().changePassword(pwd);
return true;
} catch (XMPPException e) {
e.printStackTrace();
return false;
}
}
/**
* 通过jid获得username
* @param fullUsername
* @return
*/
public static String getUsername(String fullUsername){
return fullUsername.split("@")[0];
}
/**
* 通过username获得jid
* @param username
* @return
*/
public static String getFullUsername(String username){
return username + "@" + XmppConnection.SERVER_NAME;
}
public static boolean isLogin(){
return isLogin;
}
public static void setIsLogin(boolean login){
isLogin = login;
}
/**
* 删除当前用户
* @param connection
* @return
*/
public static boolean deleteAccount(XMPPConnection connection)
{
try {
connection.getAccountManager().deleteAccount();
return true;
} catch (Exception e) {
return false;
}
}
// /**
// * 返回所有组信息
// * @return List(RosterGroup)
// */
// public static List
getGroups(Roster roster) {
// List
groupsList = new ArrayList
();
// Collection
rosterGroup = roster.getGroups(); // Iterator
i = rosterGroup.iterator(); // while (i.hasNext()) // groupsList.add(i.next()); // return groupsList; // } // /** // * 返回相应(groupName)组里的所有用户
// * @return List(RosterEntry) // */ // public static List
getEntriesByGroup(Roster roster, // String groupName) { // List
EntriesList = new ArrayList
(); // RosterGroup rosterGroup = roster.getGroup(groupName); // Collection
rosterEntry = rosterGroup.getEntries(); // Iterator
i = rosterEntry.iterator(); // while (i.hasNext()) // EntriesList.add(i.next()); // return EntriesList; // } /** * 返回所有用户信息
* @return List(RosterEntry) */ public static List
getAllEntries(Roster roster) { List
EntriesList = new ArrayList
(); Collection
rosterEntry = roster.getEntries(); Iterator
i = rosterEntry.iterator(); while (i.hasNext()) EntriesList.add(i.next()); return EntriesList; } // // /** // * 创建一个组 // */ // public static boolean addGroup(Roster roster,String groupName) // { // try { // roster.createGroup(groupName); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // /** // * 删除一个组 // */ // public static boolean removeGroup(Roster roster,String groupName) // { // return false; // } // /** * 添加一个好友 无分组 */ public static boolean addUser(Roster roster,String userName,String name) { try { roster.createEntry(userName, name, null); return true; } catch (Exception e) { e.printStackTrace(); return false; } } // /** // * 添加一个好友到分组 // * @param roster // * @param userName // * @param name // * @return // */ // public static boolean addUsers(Roster roster,String userName,String name,String groupName) // { // try { // roster.createEntry(userName, name,new String[]{ groupName}); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // // } /** * 删除一个好友 * @param roster * @param userJid * @return */ public static boolean removeUser(Roster roster,String userJid) { try { RosterEntry entry = roster.getEntry(userJid); roster.removeEntry(entry); return true; } catch (Exception e) { e.printStackTrace(); return false; } } // // /** // * 把一个好友添加到一个组中 // * @param userJid // * @param groupName // */ // public static void addUserToGroup(final String userJid, final String groupName, // final XMPPConnection connection) { // RosterGroup group = connection.getRoster().getGroup(groupName); // // 这个组已经存在就添加到这个组,不存在创建一个组 // RosterEntry entry = connection.getRoster().getEntry(userJid); // try { // if (group != null) { // if (entry != null) // group.addEntry(entry); // } else { // RosterGroup newGroup = connection.getRoster().createGroup("我的好友"); // if (entry != null) // newGroup.addEntry(entry); // } // } catch (Exception e) { // e.printStackTrace(); // } // } // /** // * 把一个好友从组中删除 // * @param userJid // * @param groupName // */ // public static void removeUserFromGroup(final String userJid,final String groupName, final XMPPConnection connection) { // RosterGroup group = connection.getRoster().getGroup(groupName); // if (group != null) { // try { // RosterEntry entry = connection.getRoster().getEntry(userJid); // if (entry != null) // group.removeEntry(entry); // } catch (XMPPException e) { // e.printStackTrace(); // } // } // } /** * 修改心情 * @param connection * @param status */ public static void changeStateMessage(final XMPPConnection connection,final String status) { Presence presence = new Presence(Presence.Type.available); presence.setStatus(status); connection.sendPacket(presence); } }
有了这两个类,你的xmpp+openfire+android+asmack之旅就很容易了
剩下的内容将会在下一次全部发布,并送上例子