Android基於XMPP Smack Openfire下學習開發IM(六)總結

http://blog.csdn.net/h7870181/article/details/12500231

不管學習什麼都應該總結

這裏我把關於Xmpp的一些方法整理到一個工具類中了

我就分享給大家


XmppConnection.java

[java] view plaincopy
  1. package com.techrare.utils;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedReader;  
  5. import java.io.ByteArrayInputStream;  
  6. import java.io.File;  
  7. import java.io.FileInputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStreamReader;  
  10. import java.net.URL;  
  11. import java.net.URLConnection;  
  12. import java.util.ArrayList;  
  13. import java.util.Collection;  
  14. import java.util.HashMap;  
  15. import java.util.Iterator;  
  16. import java.util.List;  
  17. import java.util.Map;  
  18.   
  19. import org.jivesoftware.smack.ConnectionConfiguration;  
  20. import org.jivesoftware.smack.PacketCollector;  
  21. import org.jivesoftware.smack.Roster;  
  22. import org.jivesoftware.smack.RosterEntry;  
  23. import org.jivesoftware.smack.RosterGroup;  
  24. import org.jivesoftware.smack.SmackConfiguration;  
  25. import org.jivesoftware.smack.XMPPConnection;  
  26. import org.jivesoftware.smack.XMPPException;  
  27. import org.jivesoftware.smack.filter.AndFilter;  
  28. import org.jivesoftware.smack.filter.PacketFilter;  
  29. import org.jivesoftware.smack.filter.PacketIDFilter;  
  30. import org.jivesoftware.smack.filter.PacketTypeFilter;  
  31. import org.jivesoftware.smack.packet.IQ;  
  32. import org.jivesoftware.smack.packet.Message;  
  33. import org.jivesoftware.smack.packet.Packet;  
  34. import org.jivesoftware.smack.packet.Presence;  
  35. import org.jivesoftware.smack.packet.Registration;  
  36. import org.jivesoftware.smack.provider.PrivacyProvider;  
  37. import org.jivesoftware.smack.provider.ProviderManager;  
  38. import org.jivesoftware.smack.util.StringUtils;  
  39. import org.jivesoftware.smackx.Form;  
  40. import org.jivesoftware.smackx.FormField;  
  41. import org.jivesoftware.smackx.GroupChatInvitation;  
  42. import org.jivesoftware.smackx.OfflineMessageManager;  
  43. import org.jivesoftware.smackx.PrivateDataManager;  
  44. import org.jivesoftware.smackx.ReportedData;  
  45. import org.jivesoftware.smackx.ReportedData.Row;  
  46. import org.jivesoftware.smackx.ServiceDiscoveryManager;  
  47. import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;  
  48. import org.jivesoftware.smackx.filetransfer.FileTransferManager;  
  49. import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;  
  50. import org.jivesoftware.smackx.muc.DiscussionHistory;  
  51. import org.jivesoftware.smackx.muc.HostedRoom;  
  52. import org.jivesoftware.smackx.muc.MultiUserChat;  
  53. import org.jivesoftware.smackx.packet.ChatStateExtension;  
  54. import org.jivesoftware.smackx.packet.LastActivity;  
  55. import org.jivesoftware.smackx.packet.OfflineMessageInfo;  
  56. import org.jivesoftware.smackx.packet.OfflineMessageRequest;  
  57. import org.jivesoftware.smackx.packet.SharedGroupsInfo;  
  58. import org.jivesoftware.smackx.packet.VCard;  
  59. import org.jivesoftware.smackx.provider.AdHocCommandDataProvider;  
  60. import org.jivesoftware.smackx.provider.DataFormProvider;  
  61. import org.jivesoftware.smackx.provider.DelayInformationProvider;  
  62. import org.jivesoftware.smackx.provider.DiscoverInfoProvider;  
  63. import org.jivesoftware.smackx.provider.DiscoverItemsProvider;  
  64. import org.jivesoftware.smackx.provider.MUCAdminProvider;  
  65. import org.jivesoftware.smackx.provider.MUCOwnerProvider;  
  66. import org.jivesoftware.smackx.provider.MUCUserProvider;  
  67. import org.jivesoftware.smackx.provider.MessageEventProvider;  
  68. import org.jivesoftware.smackx.provider.MultipleAddressesProvider;  
  69. import org.jivesoftware.smackx.provider.RosterExchangeProvider;  
  70. import org.jivesoftware.smackx.provider.StreamInitiationProvider;  
  71. import org.jivesoftware.smackx.provider.VCardProvider;  
  72. import org.jivesoftware.smackx.provider.XHTMLExtensionProvider;  
  73. import org.jivesoftware.smackx.search.UserSearch;  
  74. import org.jivesoftware.smackx.search.UserSearchManager;  
  75.   
  76. import android.graphics.drawable.Drawable;  
  77. import android.util.Log;  
  78.   
  79. import com.techrare.listener.TaxiConnectionListener;  
  80. /** 
  81.  * XmppConnection 工具類 
  82.  * @author 肖賽SoAi 
  83.  * 
  84.  */  
  85. public class XmppConnection {  
  86.     private int SERVER_PORT = 5222;  
  87.     private String SERVER_HOST = "127.0.0.1";  
  88.     private XMPPConnection connection = null;  
  89.     private String SERVER_NAME = "ubuntuserver4java";  
  90.     private static XmppConnection xmppConnection = new XmppConnection();  
  91.     private TaxiConnectionListener connectionListener;  
  92.     /** 
  93.      * 單例模式 
  94.      *  
  95.      * @return 
  96.      */  
  97.     synchronized public static XmppConnection getInstance() {  
  98.         return xmppConnection;  
  99.     }  
  100.   
  101.     /** 
  102.      * 創建連接 
  103.      */  
  104.     public XMPPConnection getConnection() {  
  105.         if (connection == null) {  
  106.             openConnection();  
  107.         }  
  108.         return connection;  
  109.     }  
  110.   
  111.     /** 
  112.      * 打開連接 
  113.      */  
  114.     public boolean openConnection() {  
  115.         try {  
  116.             if (null == connection || !connection.isAuthenticated()) {  
  117.                 XMPPConnection.DEBUG_ENABLED = true;// 開啓DEBUG模式  
  118.                 // 配置連接  
  119.                 ConnectionConfiguration config = new ConnectionConfiguration(  
  120.                         SERVER_HOST, SERVER_PORT, SERVER_NAME);  
  121.                 config.setReconnectionAllowed(true);  
  122.                 config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);  
  123.                 config.setSendPresence(true); // 狀態設爲離線,目的爲了取離線消息  
  124.                 config.setSASLAuthenticationEnabled(false); // 是否啓用安全驗證  
  125.                 config.setTruststorePath("/system/etc/security/cacerts.bks");  
  126.                 config.setTruststorePassword("changeit");  
  127.                 config.setTruststoreType("bks");  
  128.                 connection = new XMPPConnection(config);  
  129.                 connection.connect();// 連接到服務器  
  130.                 // 配置各種Provider,如果不配置,則會無法解析數據  
  131.                 configureConnection(ProviderManager.getInstance());  
  132.                 return true;  
  133.             }  
  134.         } catch (XMPPException xe) {  
  135.             xe.printStackTrace();  
  136.             connection = null;  
  137.         }  
  138.         return false;  
  139.     }  
  140.   
  141.     /** 
  142.      * 關閉連接 
  143.      */  
  144.     public void closeConnection() {  
  145.         if(connection!=null){  
  146.             //移除連接監聽  
  147.             //connection.removeConnectionListener(connectionListener);  
  148.             if(connection.isConnected())  
  149.                 connection.disconnect();  
  150.             connection = null;  
  151.         }  
  152.         Log.i("XmppConnection""關閉連接");  
  153.     }  
  154.   
  155.     /** 
  156.      * 登錄 
  157.      *  
  158.      * @param account 
  159.      *            登錄帳號 
  160.      * @param password 
  161.      *            登錄密碼 
  162.      * @return 
  163.      */  
  164.     public boolean login(String account, String password) {  
  165.         try {  
  166.             if (getConnection() == null)  
  167.                 return false;  
  168.             getConnection().login(account, password);  
  169.             // 更改在綫狀態  
  170.             Presence presence = new Presence(Presence.Type.available);  
  171.             getConnection().sendPacket(presence);  
  172.             // 添加連接監聽  
  173.             connectionListener = new TaxiConnectionListener();  
  174.             getConnection().addConnectionListener(connectionListener);  
  175.             return true;  
  176.         } catch (XMPPException xe) {  
  177.             xe.printStackTrace();  
  178.         }  
  179.         return false;  
  180.     }  
  181.   
  182.     /** 
  183.      * 註冊 
  184.      *  
  185.      * @param account 
  186.      *            註冊帳號 
  187.      * @param password 
  188.      *            註冊密碼 
  189.      * @return 1、註冊成功 0、服務器沒有返回結果2、這個賬號已經存在3、註冊失敗 
  190.      */  
  191.     public String regist(String account, String password) {  
  192.         if (getConnection() == null)  
  193.             return "0";  
  194.         Registration reg = new Registration();  
  195.         reg.setType(IQ.Type.SET);  
  196.         reg.setTo(getConnection().getServiceName());  
  197.         // 注意這裏createAccount註冊時,參數是UserName,不是jid,是"@"前面的部分。  
  198.         reg.setUsername(account);  
  199.         reg.setPassword(password);  
  200.         // 這邊addAttribute不能爲空,否則出錯。所以做個標誌是android手機創建的吧!!!!!  
  201.         reg.addAttribute("android""geolo_createUser_android");  
  202.         PacketFilter filter = new AndFilter(new PacketIDFilter(  
  203.                 reg.getPacketID()), new PacketTypeFilter(IQ.class));  
  204.         PacketCollector collector = getConnection().createPacketCollector(  
  205.                 filter);  
  206.         getConnection().sendPacket(reg);  
  207.         IQ result = (IQ) collector.nextResult(SmackConfiguration  
  208.                 .getPacketReplyTimeout());  
  209.         // Stop queuing results停止請求results(是否成功的結果)  
  210.         collector.cancel();  
  211.         if (result == null) {  
  212.             Log.e("regist""No response from server.");  
  213.             return "0";  
  214.         } else if (result.getType() == IQ.Type.RESULT) {  
  215.             Log.v("regist""regist success.");  
  216.             return "1";  
  217.         } else { // if (result.getType() == IQ.Type.ERROR)  
  218.             if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {  
  219.                 Log.e("regist""IQ.Type.ERROR: "  
  220.                         + result.getError().toString());  
  221.                 return "2";  
  222.             } else {  
  223.                 Log.e("regist""IQ.Type.ERROR: "  
  224.                         + result.getError().toString());  
  225.                 return "3";  
  226.             }  
  227.         }  
  228.     }  
  229.   
  230.     /** 
  231.      * 更改用戶狀態 
  232.      */  
  233.     public void setPresence(int code) {  
  234.         XMPPConnection con = getConnection();  
  235.         if (con == null)  
  236.             return;  
  237.         Presence presence;  
  238.         switch (code) {  
  239.         case 0:  
  240.             presence = new Presence(Presence.Type.available);  
  241.             con.sendPacket(presence);  
  242.             Log.v("state""設置在線");  
  243.             break;  
  244.         case 1:  
  245.             presence = new Presence(Presence.Type.available);  
  246.             presence.setMode(Presence.Mode.chat);  
  247.             con.sendPacket(presence);  
  248.             Log.v("state""設置Q我吧");  
  249.             break;  
  250.         case 2:  
  251.             presence = new Presence(Presence.Type.available);  
  252.             presence.setMode(Presence.Mode.dnd);  
  253.             con.sendPacket(presence);  
  254.             Log.v("state""設置忙碌");  
  255.             break;  
  256.         case 3:  
  257.             presence = new Presence(Presence.Type.available);  
  258.             presence.setMode(Presence.Mode.away);  
  259.             con.sendPacket(presence);  
  260.             Log.v("state""設置離開");  
  261.             break;  
  262.         case 4:  
  263.             Roster roster = con.getRoster();  
  264.             Collection<RosterEntry> entries = roster.getEntries();  
  265.             for (RosterEntry entry : entries) {  
  266.                 presence = new Presence(Presence.Type.unavailable);  
  267.                 presence.setPacketID(Packet.ID_NOT_AVAILABLE);  
  268.                 presence.setFrom(con.getUser());  
  269.                 presence.setTo(entry.getUser());  
  270.                 con.sendPacket(presence);  
  271.                 Log.v("state", presence.toXML());  
  272.             }  
  273.             // 向同一用戶的其他客戶端發送隱身狀態  
  274.             presence = new Presence(Presence.Type.unavailable);  
  275.             presence.setPacketID(Packet.ID_NOT_AVAILABLE);  
  276.             presence.setFrom(con.getUser());  
  277.             presence.setTo(StringUtils.parseBareAddress(con.getUser()));  
  278.             con.sendPacket(presence);  
  279.             Log.v("state""設置隱身");  
  280.             break;  
  281.         case 5:  
  282.             presence = new Presence(Presence.Type.unavailable);  
  283.             con.sendPacket(presence);  
  284.             Log.v("state""設置離線");  
  285.             break;  
  286.         default:  
  287.             break;  
  288.         }  
  289.     }  
  290.   
  291.     /** 
  292.      * 獲取所有組 
  293.      *  
  294.      * @return 所有組集合 
  295.      */  
  296.     public List<RosterGroup> getGroups() {  
  297.         if (getConnection() == null)  
  298.             return null;  
  299.         List<RosterGroup> grouplist = new ArrayList<RosterGroup>();  
  300.         Collection<RosterGroup> rosterGroup = getConnection().getRoster()  
  301.                 .getGroups();  
  302.         Iterator<RosterGroup> i = rosterGroup.iterator();  
  303.         while (i.hasNext()) {  
  304.             grouplist.add(i.next());  
  305.         }  
  306.         return grouplist;  
  307.     }  
  308.   
  309.     /** 
  310.      * 獲取某個組裏面的所有好友 
  311.      *  
  312.      * @param roster 
  313.      * @param groupName 
  314.      *            組名 
  315.      * @return 
  316.      */  
  317.     public List<RosterEntry> getEntriesByGroup(String groupName) {  
  318.         if (getConnection() == null)  
  319.             return null;  
  320.         List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();  
  321.         RosterGroup rosterGroup = getConnection().getRoster().getGroup(  
  322.                 groupName);  
  323.         Collection<RosterEntry> rosterEntry = rosterGroup.getEntries();  
  324.         Iterator<RosterEntry> i = rosterEntry.iterator();  
  325.         while (i.hasNext()) {  
  326.             Entrieslist.add(i.next());  
  327.         }  
  328.         return Entrieslist;  
  329.     }  
  330.   
  331.     /** 
  332.      * 獲取所有好友信息 
  333.      *  
  334.      * @return 
  335.      */  
  336.     public List<RosterEntry> getAllEntries() {  
  337.         if (getConnection() == null)  
  338.             return null;  
  339.         List<RosterEntry> Entrieslist = new ArrayList<RosterEntry>();  
  340.         Collection<RosterEntry> rosterEntry = getConnection().getRoster()  
  341.                 .getEntries();  
  342.         Iterator<RosterEntry> i = rosterEntry.iterator();  
  343.         while (i.hasNext()) {  
  344.             Entrieslist.add(i.next());  
  345.         }  
  346.         return Entrieslist;  
  347.     }  
  348.   
  349.     /** 
  350.      * 獲取用戶VCard信息 
  351.      *  
  352.      * @param connection 
  353.      * @param user 
  354.      * @return 
  355.      * @throws XMPPException 
  356.      */  
  357.     public VCard getUserVCard(String user) {  
  358.         if (getConnection() == null)  
  359.             return null;  
  360.         VCard vcard = new VCard();  
  361.         try {  
  362.             vcard.load(getConnection(), user);  
  363.         } catch (XMPPException e) {  
  364.             e.printStackTrace();  
  365.         }  
  366.         return vcard;  
  367.     }  
  368.   
  369.     /** 
  370.      * 獲取用戶頭像信息 
  371.      *  
  372.      * @param connection 
  373.      * @param user 
  374.      * @return 
  375.      */  
  376.     public Drawable getUserImage(String user) {  
  377.         if (getConnection() == null)  
  378.             return null;  
  379.         ByteArrayInputStream bais = null;  
  380.         try {  
  381.             VCard vcard = new VCard();  
  382.             // 加入這句代碼,解決No VCard for  
  383.             ProviderManager.getInstance().addIQProvider("vCard""vcard-temp",  
  384.                     new org.jivesoftware.smackx.provider.VCardProvider());  
  385.             if (user == "" || user == null || user.trim().length() <= 0) {  
  386.                 return null;  
  387.             }  
  388.             vcard.load(getConnection(), user + "@"  
  389.                     + getConnection().getServiceName());  
  390.   
  391.             if (vcard == null || vcard.getAvatar() == null)  
  392.                 return null;  
  393.             bais = new ByteArrayInputStream(vcard.getAvatar());  
  394.         } catch (Exception e) {  
  395.             e.printStackTrace();  
  396.             return null;  
  397.         }  
  398.         return FormatTools.getInstance().InputStream2Drawable(bais);  
  399.     }  
  400.   
  401.     /** 
  402.      * 添加一個分組 
  403.      *  
  404.      * @param groupName 
  405.      * @return 
  406.      */  
  407.     public boolean addGroup(String groupName) {  
  408.         if (getConnection() == null)  
  409.             return false;  
  410.         try {  
  411.             getConnection().getRoster().createGroup(groupName);  
  412.             Log.v("addGroup", groupName + "創建成功");  
  413.             return true;  
  414.         } catch (Exception e) {  
  415.             e.printStackTrace();  
  416.             return false;  
  417.         }  
  418.     }  
  419.   
  420.     /** 
  421.      * 刪除分組 
  422.      *  
  423.      * @param groupName 
  424.      * @return 
  425.      */  
  426.     public boolean removeGroup(String groupName) {  
  427.         return true;  
  428.     }  
  429.   
  430.     /** 
  431.      * 添加好友 無分組 
  432.      *  
  433.      * @param userName 
  434.      * @param name 
  435.      * @return 
  436.      */  
  437.     public boolean addUser(String userName, String name) {  
  438.         if (getConnection() == null)  
  439.             return false;  
  440.         try {  
  441.             getConnection().getRoster().createEntry(userName, name, null);  
  442.             return true;  
  443.         } catch (Exception e) {  
  444.             e.printStackTrace();  
  445.             return false;  
  446.         }  
  447.     }  
  448.   
  449.     /** 
  450.      * 添加好友 有分組 
  451.      *  
  452.      * @param userName 
  453.      * @param name 
  454.      * @param groupName 
  455.      * @return 
  456.      */  
  457.     public boolean addUser(String userName, String name, String groupName) {  
  458.         if (getConnection() == null)  
  459.             return false;  
  460.         try {  
  461.             Presence subscription = new Presence(Presence.Type.subscribed);  
  462.             subscription.setTo(userName);  
  463.             userName += "@" + getConnection().getServiceName();  
  464.             getConnection().sendPacket(subscription);  
  465.             getConnection().getRoster().createEntry(userName, name,  
  466.                     new String[] { groupName });  
  467.             return true;  
  468.         } catch (Exception e) {  
  469.             e.printStackTrace();  
  470.             return false;  
  471.         }  
  472.     }  
  473.   
  474.     /** 
  475.      * 刪除好友 
  476.      *  
  477.      * @param userName 
  478.      * @return 
  479.      */  
  480.     public boolean removeUser(String userName) {  
  481.         if (getConnection() == null)  
  482.             return false;  
  483.         try {  
  484.             RosterEntry entry = null;  
  485.             if (userName.contains("@"))  
  486.                 entry = getConnection().getRoster().getEntry(userName);  
  487.             else  
  488.                 entry = getConnection().getRoster().getEntry(  
  489.                         userName + "@" + getConnection().getServiceName());  
  490.             if (entry == null)  
  491.                 entry = getConnection().getRoster().getEntry(userName);  
  492.             getConnection().getRoster().removeEntry(entry);  
  493.   
  494.             return true;  
  495.         } catch (Exception e) {  
  496.             e.printStackTrace();  
  497.             return false;  
  498.         }  
  499.     }  
  500.   
  501.     /** 
  502.      * 查詢用戶 
  503.      *  
  504.      * @param userName 
  505.      * @return 
  506.      * @throws XMPPException 
  507.      */  
  508.     public List<HashMap<String, String>> searchUsers(String userName) {  
  509.         if (getConnection() == null)  
  510.             return null;  
  511.         HashMap<String, String> user = null;  
  512.         List<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();  
  513.         try {  
  514.             new ServiceDiscoveryManager(getConnection());  
  515.   
  516.             UserSearchManager usm = new UserSearchManager(getConnection());  
  517.   
  518.             Form searchForm = usm.getSearchForm(getConnection()  
  519.                     .getServiceName());  
  520.             Form answerForm = searchForm.createAnswerForm();  
  521.             answerForm.setAnswer("userAccount"true);  
  522.             answerForm.setAnswer("userPhote", userName);  
  523.             ReportedData data = usm.getSearchResults(answerForm, "search"  
  524.                     + getConnection().getServiceName());  
  525.   
  526.             Iterator<Row> it = data.getRows();  
  527.             Row row = null;  
  528.             while (it.hasNext()) {  
  529.                 user = new HashMap<String, String>();  
  530.                 row = it.next();  
  531.                 user.put("userAccount", row.getValues("userAccount").next()  
  532.                         .toString());  
  533.                 user.put("userPhote", row.getValues("userPhote").next()  
  534.                         .toString());  
  535.                 results.add(user);  
  536.                 // 若存在,則有返回,UserName一定非空,其他兩個若是有設,一定非空  
  537.             }  
  538.         } catch (XMPPException e) {  
  539.             e.printStackTrace();  
  540.         }  
  541.         return results;  
  542.     }  
  543.   
  544.     /** 
  545.      * 修改心情 
  546.      *  
  547.      * @param connection 
  548.      * @param status 
  549.      */  
  550.     public void changeStateMessage(String status) {  
  551.         if (getConnection() == null)  
  552.             return;  
  553.         Presence presence = new Presence(Presence.Type.available);  
  554.         presence.setStatus(status);  
  555.         getConnection().sendPacket(presence);  
  556.     }  
  557.   
  558.     /** 
  559.      * 修改用戶頭像 
  560.      *  
  561.      * @param file 
  562.      */  
  563.     public boolean changeImage(File file) {  
  564.         if (getConnection() == null)  
  565.             return false;  
  566.         try {  
  567.             VCard vcard = new VCard();  
  568.             vcard.load(getConnection());  
  569.   
  570.             byte[] bytes;  
  571.   
  572.             bytes = getFileBytes(file);  
  573.             String encodedImage = StringUtils.encodeBase64(bytes);  
  574.             vcard.setAvatar(bytes, encodedImage);  
  575.             vcard.setEncodedImage(encodedImage);  
  576.             vcard.setField("PHOTO""<TYPE>image/jpg</TYPE><BINVAL>"  
  577.                     + encodedImage + "</BINVAL>"true);  
  578.   
  579.             ByteArrayInputStream bais = new ByteArrayInputStream(  
  580.                     vcard.getAvatar());  
  581.             FormatTools.getInstance().InputStream2Bitmap(bais);  
  582.   
  583.             vcard.save(getConnection());  
  584.             return true;  
  585.         } catch (Exception e) {  
  586.             e.printStackTrace();  
  587.             return false;  
  588.         }  
  589.     }  
  590.   
  591.     /** 
  592.      * 文件轉字節 
  593.      *  
  594.      * @param file 
  595.      * @return 
  596.      * @throws IOException 
  597.      */  
  598.     private byte[] getFileBytes(File file) throws IOException {  
  599.         BufferedInputStream bis = null;  
  600.         try {  
  601.             bis = new BufferedInputStream(new FileInputStream(file));  
  602.             int bytes = (int) file.length();  
  603.             byte[] buffer = new byte[bytes];  
  604.             int readBytes = bis.read(buffer);  
  605.             if (readBytes != buffer.length) {  
  606.                 throw new IOException("Entire file not read");  
  607.             }  
  608.             return buffer;  
  609.         } finally {  
  610.             if (bis != null) {  
  611.                 bis.close();  
  612.             }  
  613.         }  
  614.     }  
  615.   
  616.     /** 
  617.      * 刪除當前用戶 
  618.      *  
  619.      * @return 
  620.      */  
  621.     public boolean deleteAccount() {  
  622.         if (getConnection() == null)  
  623.             return false;  
  624.         try {  
  625.             getConnection().getAccountManager().deleteAccount();  
  626.             return true;  
  627.         } catch (XMPPException e) {  
  628.             return false;  
  629.         }  
  630.     }  
  631.   
  632.     /** 
  633.      * 修改密碼 
  634.      *  
  635.      * @return 
  636.      */  
  637.     public boolean changePassword(String pwd) {  
  638.         if (getConnection() == null)  
  639.             return false;  
  640.         try {  
  641.             getConnection().getAccountManager().changePassword(pwd);  
  642.             return true;  
  643.         } catch (XMPPException e) {  
  644.             return false;  
  645.         }  
  646.     }  
  647.   
  648.     /** 
  649.      * 初始化會議室列表 
  650.      */  
  651.     public List<HostedRoom> getHostRooms() {  
  652.         if (getConnection() == null)  
  653.             return null;  
  654.         Collection<HostedRoom> hostrooms = null;  
  655.         List<HostedRoom> roominfos = new ArrayList<HostedRoom>();  
  656.         try {  
  657.             new ServiceDiscoveryManager(getConnection());  
  658.             hostrooms = MultiUserChat.getHostedRooms(getConnection(),  
  659.                     getConnection().getServiceName());  
  660.             for (HostedRoom entry : hostrooms) {  
  661.                 roominfos.add(entry);  
  662.                 Log.i("room",  
  663.                         "名字:" + entry.getName() + " - ID:" + entry.getJid());  
  664.             }  
  665.             Log.i("room""服務會議數量:" + roominfos.size());  
  666.         } catch (XMPPException e) {  
  667.             e.printStackTrace();  
  668.         }  
  669.         return roominfos;  
  670.     }  
  671.   
  672.     /** 
  673.      * 創建房間 
  674.      *  
  675.      * @param roomName 
  676.      *            房間名稱 
  677.      */  
  678.     public MultiUserChat createRoom(String user, String roomName,  
  679.             String password) {  
  680.         if (getConnection() == null)  
  681.             return null;  
  682.   
  683.         MultiUserChat muc = null;  
  684.         try {  
  685.             // 創建一個MultiUserChat  
  686.             muc = new MultiUserChat(getConnection(), roomName + "@conference."  
  687.                     + getConnection().getServiceName());  
  688.             // 創建聊天室  
  689.             muc.create(roomName);  
  690.             // 獲得聊天室的配置表單  
  691.             Form form = muc.getConfigurationForm();  
  692.             // 根據原始表單創建一個要提交的新表單。  
  693.             Form submitForm = form.createAnswerForm();  
  694.             // 向要提交的表單添加默認答覆  
  695.             for (Iterator<FormField> fields = form.getFields(); fields  
  696.                     .hasNext();) {  
  697.                 FormField field = (FormField) fields.next();  
  698.                 if (!FormField.TYPE_HIDDEN.equals(field.getType())  
  699.                         && field.getVariable() != null) {  
  700.                     // 設置默認值作爲答覆  
  701.                     submitForm.setDefaultAnswer(field.getVariable());  
  702.                 }  
  703.             }  
  704.             // 設置聊天室的新擁有者  
  705.             List<String> owners = new ArrayList<String>();  
  706.             owners.add(getConnection().getUser());// 用戶JID  
  707.             submitForm.setAnswer("muc#roomconfig_roomowners", owners);  
  708.             // 設置聊天室是持久聊天室,即將要被保存下來  
  709.             submitForm.setAnswer("muc#roomconfig_persistentroom"true);  
  710.             // 房間僅對成員開放  
  711.             submitForm.setAnswer("muc#roomconfig_membersonly"false);  
  712.             // 允許佔有者邀請其他人  
  713.             submitForm.setAnswer("muc#roomconfig_allowinvites"true);  
  714.             if (!password.equals("")) {  
  715.                 // 進入是否需要密碼  
  716.                 submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",  
  717.                         true);  
  718.                 // 設置進入密碼  
  719.                 submitForm.setAnswer("muc#roomconfig_roomsecret", password);  
  720.             }  
  721.             // 能夠發現佔有者真實 JID 的角色  
  722.             // submitForm.setAnswer("muc#roomconfig_whois", "anyone");  
  723.             // 登錄房間對話  
  724.             submitForm.setAnswer("muc#roomconfig_enablelogging"true);  
  725.             // 僅允許註冊的暱稱登錄  
  726.             submitForm.setAnswer("x-muc#roomconfig_reservednick"true);  
  727.             // 允許使用者修改暱稱  
  728.             submitForm.setAnswer("x-muc#roomconfig_canchangenick"false);  
  729.             // 允許用戶註冊房間  
  730.             submitForm.setAnswer("x-muc#roomconfig_registration"false);  
  731.             // 發送已完成的表單(有默認值)到服務器來配置聊天室  
  732.             muc.sendConfigurationForm(submitForm);  
  733.         } catch (XMPPException e) {  
  734.             e.printStackTrace();  
  735.             return null;  
  736.         }  
  737.         return muc;  
  738.     }  
  739.   
  740.     /** 
  741.      * 加入會議室 
  742.      *  
  743.      * @param user 
  744.      *            暱稱 
  745.      * @param password 
  746.      *            會議室密碼 
  747.      * @param roomsName 
  748.      *            會議室名 
  749.      */  
  750.     public MultiUserChat joinMultiUserChat(String user, String roomsName,  
  751.             String password) {  
  752.         if (getConnection() == null)  
  753.             return null;  
  754.         try {  
  755.             // 使用XMPPConnection創建一個MultiUserChat窗口  
  756.             MultiUserChat muc = new MultiUserChat(getConnection(), roomsName  
  757.                     + "@conference." + getConnection().getServiceName());  
  758.             // 聊天室服務將會決定要接受的歷史記錄數量  
  759.             DiscussionHistory history = new DiscussionHistory();  
  760.             history.setMaxChars(0);  
  761.             // history.setSince(new Date());  
  762.             // 用戶加入聊天室  
  763.             muc.join(user, password, history,  
  764.                     SmackConfiguration.getPacketReplyTimeout());  
  765.             Log.i("MultiUserChat""會議室【"+roomsName+"】加入成功........");  
  766.             return muc;  
  767.         } catch (XMPPException e) {  
  768.             e.printStackTrace();  
  769.             Log.i("MultiUserChat""會議室【"+roomsName+"】加入失敗........");  
  770.             return null;  
  771.         }  
  772.     }  
  773.   
  774.     /** 
  775.      * 查詢會議室成員名字 
  776.      *  
  777.      * @param muc 
  778.      */  
  779.     public List<String> findMulitUser(MultiUserChat muc) {  
  780.         if (getConnection() == null)  
  781.             return null;  
  782.         List<String> listUser = new ArrayList<String>();  
  783.         Iterator<String> it = muc.getOccupants();  
  784.         // 遍歷出聊天室人員名稱  
  785.         while (it.hasNext()) {  
  786.             // 聊天室成員名字  
  787.             String name = StringUtils.parseResource(it.next());  
  788.             listUser.add(name);  
  789.         }  
  790.         return listUser;  
  791.     }  
  792.   
  793.     /** 
  794.      * 發送文件 
  795.      *  
  796.      * @param user 
  797.      * @param filePath 
  798.      */  
  799.     public void sendFile(String user, String filePath) {  
  800.         if (getConnection() == null)  
  801.             return;  
  802.         // 創建文件傳輸管理器  
  803.         FileTransferManager manager = new FileTransferManager(getConnection());  
  804.   
  805.         // 創建輸出的文件傳輸  
  806.         OutgoingFileTransfer transfer = manager  
  807.                 .createOutgoingFileTransfer(user);  
  808.   
  809.         // 發送文件  
  810.         try {  
  811.             transfer.sendFile(new File(filePath), "You won't believe this!");  
  812.         } catch (XMPPException e) {  
  813.             e.printStackTrace();  
  814.         }  
  815.     }  
  816.   
  817.     /** 
  818.      * 獲取離線消息 
  819.      *  
  820.      * @return 
  821.      */  
  822.     public Map<String, List<HashMap<String, String>>> getHisMessage() {  
  823.         if (getConnection() == null)  
  824.             return null;  
  825.         Map<String, List<HashMap<String, String>>> offlineMsgs = null;  
  826.   
  827.         try {  
  828.             OfflineMessageManager offlineManager = new OfflineMessageManager(  
  829.                     getConnection());  
  830.             Iterator<Message> it = offlineManager.getMessages();  
  831.   
  832.             int count = offlineManager.getMessageCount();  
  833.             if (count <= 0)  
  834.                 return null;  
  835.             offlineMsgs = new HashMap<String, List<HashMap<String, String>>>();  
  836.   
  837.             while (it.hasNext()) {  
  838.                 Message message = it.next();  
  839.                 String fromUser = StringUtils.parseName(message.getFrom());  
  840.                 ;  
  841.                 HashMap<String, String> histrory = new HashMap<String, String>();  
  842.                 histrory.put("useraccount",  
  843.                         StringUtils.parseName(getConnection().getUser()));  
  844.                 histrory.put("friendaccount", fromUser);  
  845.                 histrory.put("info", message.getBody());  
  846.                 histrory.put("type""left");  
  847.                 if (offlineMsgs.containsKey(fromUser)) {  
  848.                     offlineMsgs.get(fromUser).add(histrory);  
  849.                 } else {  
  850.                     List<HashMap<String, String>> temp = new ArrayList<HashMap<String, String>>();  
  851.                     temp.add(histrory);  
  852.                     offlineMsgs.put(fromUser, temp);  
  853.                 }  
  854.             }  
  855.             offlineManager.deleteMessages();  
  856.         } catch (Exception e) {  
  857.             e.printStackTrace();  
  858.         }  
  859.         return offlineMsgs;  
  860.     }  
  861.       
  862.     /** 
  863.      * 判斷OpenFire用戶的狀態 strUrl :  
  864.      * url格式 - http://my.openfire.com:9090/plugins/presence 
  865.      * /status?jid=user1@SERVER_NAME&type=xml  
  866.      * 返回值 : 0 - 用戶不存在; 1 - 用戶在線; 2 - 用戶離線  
  867.      * 說明 :必須要求 OpenFire加載 presence 插件,同時設置任何人都可以訪問 
  868.      */     
  869.     public int IsUserOnLine(String user) {  
  870.         String url = "http://"+SERVER_HOST+":9090/plugins/presence/status?" +  
  871.                 "jid="+ user +"@"+ SERVER_NAME +"&type=xml";  
  872.         int shOnLineState = 0// 不存在  
  873.         try {  
  874.             URL oUrl = new URL(url);  
  875.             URLConnection oConn = oUrl.openConnection();  
  876.             if (oConn != null) {  
  877.                 BufferedReader oIn = new BufferedReader(new InputStreamReader(  
  878.                         oConn.getInputStream()));  
  879.                 if (null != oIn) {  
  880.                     String strFlag = oIn.readLine();  
  881.                     oIn.close();  
  882.                     System.out.println("strFlag"+strFlag);  
  883.                     if (strFlag.indexOf("type=\"unavailable\"") >= 0) {  
  884.                         shOnLineState = 2;  
  885.                     }  
  886.                     if (strFlag.indexOf("type=\"error\"") >= 0) {  
  887.                         shOnLineState = 0;  
  888.                     } else if (strFlag.indexOf("priority") >= 0  
  889.                             || strFlag.indexOf("id=\"") >= 0) {  
  890.                         shOnLineState = 1;  
  891.                     }  
  892.                 }  
  893.             }  
  894.         } catch (Exception e) {  
  895.             e.printStackTrace();  
  896.         }  
  897.   
  898.         return shOnLineState;  
  899.     }  
  900.   
  901.     /** 
  902.      * 加入providers的函數 ASmack在/META-INF缺少一個smack.providers 文件 
  903.      *  
  904.      * @param pm 
  905.      */  
  906.     public void configureConnection(ProviderManager pm) {  
  907.   
  908.         // Private Data Storage  
  909.         pm.addIQProvider("query""jabber:iq:private",  
  910.                 new PrivateDataManager.PrivateDataIQProvider());  
  911.   
  912.         // Time  
  913.         try {  
  914.             pm.addIQProvider("query""jabber:iq:time",  
  915.                     Class.forName("org.jivesoftware.smackx.packet.Time"));  
  916.         } catch (ClassNotFoundException e) {  
  917.             Log.w("TestClient",  
  918.                     "Can't load class for org.jivesoftware.smackx.packet.Time");  
  919.         }  
  920.   
  921.         // Roster Exchange  
  922.         pm.addExtensionProvider("x""jabber:x:roster",  
  923.                 new RosterExchangeProvider());  
  924.   
  925.         // Message Events  
  926.         pm.addExtensionProvider("x""jabber:x:event",  
  927.                 new MessageEventProvider());  
  928.   
  929.         // Chat State  
  930.         pm.addExtensionProvider("active",  
  931.                 "http://jabber.org/protocol/chatstates",  
  932.                 new ChatStateExtension.Provider());  
  933.         pm.addExtensionProvider("composing",  
  934.                 "http://jabber.org/protocol/chatstates",  
  935.                 new ChatStateExtension.Provider());  
  936.         pm.addExtensionProvider("paused",  
  937.                 "http://jabber.org/protocol/chatstates",  
  938.                 new ChatStateExtension.Provider());  
  939.         pm.addExtensionProvider("inactive",  
  940.                 "http://jabber.org/protocol/chatstates",  
  941.                 new ChatStateExtension.Provider());  
  942.         pm.addExtensionProvider("gone",  
  943.                 "http://jabber.org/protocol/chatstates",  
  944.                 new ChatStateExtension.Provider());  
  945.   
  946.         // XHTML  
  947.         pm.addExtensionProvider("html""http://jabber.org/protocol/xhtml-im",  
  948.                 new XHTMLExtensionProvider());  
  949.   
  950.         // Group Chat Invitations  
  951.         pm.addExtensionProvider("x""jabber:x:conference",  
  952.                 new GroupChatInvitation.Provider());  
  953.   
  954.         // Service Discovery # Items  
  955.         pm.addIQProvider("query""http://jabber.org/protocol/disco#items",  
  956.                 new DiscoverItemsProvider());  
  957.   
  958.         // Service Discovery # Info  
  959.         pm.addIQProvider("query""http://jabber.org/protocol/disco#info",  
  960.                 new DiscoverInfoProvider());  
  961.   
  962.         // Data Forms  
  963.         pm.addExtensionProvider("x""jabber:x:data"new DataFormProvider());  
  964.   
  965.         // MUC User  
  966.         pm.addExtensionProvider("x""http://jabber.org/protocol/muc#user",  
  967.                 new MUCUserProvider());  
  968.   
  969.         // MUC Admin  
  970.         pm.addIQProvider("query""http://jabber.org/protocol/muc#admin",  
  971.                 new MUCAdminProvider());  
  972.   
  973.         // MUC Owner  
  974.         pm.addIQProvider("query""http://jabber.org/protocol/muc#owner",  
  975.                 new MUCOwnerProvider());  
  976.   
  977.         // Delayed Delivery  
  978.         pm.addExtensionProvider("x""jabber:x:delay",  
  979.                 new DelayInformationProvider());  
  980.   
  981.         // Version  
  982.         try {  
  983.             pm.addIQProvider("query""jabber:iq:version",  
  984.                     Class.forName("org.jivesoftware.smackx.packet.Version"));  
  985.         } catch (ClassNotFoundException e) {  
  986.             // Not sure what's happening here.  
  987.         }  
  988.   
  989.         // VCard  
  990.         pm.addIQProvider("vCard""vcard-temp"new VCardProvider());  
  991.   
  992.         // Offline Message Requests  
  993.         pm.addIQProvider("offline""http://jabber.org/protocol/offline",  
  994.                 new OfflineMessageRequest.Provider());  
  995.   
  996.         // Offline Message Indicator  
  997.         pm.addExtensionProvider("offline",  
  998.                 "http://jabber.org/protocol/offline",  
  999.                 new OfflineMessageInfo.Provider());  
  1000.   
  1001.         // Last Activity  
  1002.         pm.addIQProvider("query""jabber:iq:last"new LastActivity.Provider());  
  1003.   
  1004.         // User Search  
  1005.         pm.addIQProvider("query""jabber:iq:search"new UserSearch.Provider());  
  1006.   
  1007.         // SharedGroupsInfo  
  1008.         pm.addIQProvider("sharedgroup",  
  1009.                 "http://www.jivesoftware.org/protocol/sharedgroup",  
  1010.                 new SharedGroupsInfo.Provider());  
  1011.   
  1012.         // JEP-33: Extended Stanza Addressing  
  1013.         pm.addExtensionProvider("addresses",  
  1014.                 "http://jabber.org/protocol/address",  
  1015.                 new MultipleAddressesProvider());  
  1016.   
  1017.         // FileTransfer  
  1018.         pm.addIQProvider("si""http://jabber.org/protocol/si",  
  1019.                 new StreamInitiationProvider());  
  1020.   
  1021.         pm.addIQProvider("query""http://jabber.org/protocol/bytestreams",  
  1022.                 new BytestreamsProvider());  
  1023.   
  1024.         // Privacy  
  1025.         pm.addIQProvider("query""jabber:iq:privacy"new PrivacyProvider());  
  1026.         pm.addIQProvider("command""http://jabber.org/protocol/commands",  
  1027.                 new AdHocCommandDataProvider());  
  1028.         pm.addExtensionProvider("malformed-action",  
  1029.                 "http://jabber.org/protocol/commands",  
  1030.                 new AdHocCommandDataProvider.MalformedActionError());  
  1031.         pm.addExtensionProvider("bad-locale",  
  1032.                 "http://jabber.org/protocol/commands",  
  1033.                 new AdHocCommandDataProvider.BadLocaleError());  
  1034.         pm.addExtensionProvider("bad-payload",  
  1035.                 "http://jabber.org/protocol/commands",  
  1036.                 new AdHocCommandDataProvider.BadPayloadError());  
  1037.         pm.addExtensionProvider("bad-sessionid",  
  1038.                 "http://jabber.org/protocol/commands",  
  1039.                 new AdHocCommandDataProvider.BadSessionIDError());  
  1040.         pm.addExtensionProvider("session-expired",  
  1041.                 "http://jabber.org/protocol/commands",  
  1042.                 new AdHocCommandDataProvider.SessionExpiredError());  
  1043.     }  
  1044.   
  1045. }  
  1046.     /** 
  1047.      * 判斷OpenFire用戶的狀態 strUrl :  
  1048.      * url格式 - http://my.openfire.com:9090/plugins/presence 
  1049.      * /status?jid=user1@SERVER_NAME&type=xml  
  1050.      * 返回值 : 0 - 用戶不存在; 1 - 用戶在線; 2 - 用戶離線  
  1051.      * 說明 :必須要求 OpenFire加載 presence 插件,同時設置任何人都可以訪問 
  1052.      */     
  1053.     public int IsUserOnLine(String user) {  
  1054.         String url = "http://"+SERVER_HOST+":9090/plugins/presence/status?" +  
  1055.                 "jid="+ user +"@"+ SERVER_NAME +"&type=xml";  
  1056.         int shOnLineState = 0// 不存在  
  1057.         try {  
  1058.             URL oUrl = new URL(url);  
  1059.             URLConnection oConn = oUrl.openConnection();  
  1060.             if (oConn != null) {  
  1061.                 BufferedReader oIn = new BufferedReader(new InputStreamReader(  
  1062.                         oConn.getInputStream()));  
  1063.                 if (null != oIn) {  
  1064.                     String strFlag = oIn.readLine();  
  1065.                     oIn.close();  
  1066.                     System.out.println("strFlag"+strFlag);  
  1067.                     if (strFlag.indexOf("type=\"unavailable\"") >= 0) {  
  1068.                         shOnLineState = 2;  
  1069.                     }  
  1070.                     if (strFlag.indexOf("type=\"error\"") >= 0) {  
  1071.                         shOnLineState = 0;  
  1072.                     } else if (strFlag.indexOf("priority") >= 0  
  1073.                             || strFlag.indexOf("id=\"") >= 0) {  
  1074.                         shOnLineState = 1;  
  1075.                     }  
  1076.                 }  
  1077.             }  
  1078.         } catch (Exception e) {  
  1079.             e.printStackTrace();  
  1080.         }  
  1081.         return shOnLineState;  
  1082.     }  



調用該工具類的方法很簡單,用了一個單例模式,裏面的方法都可以用相同的方法調用

[java] view plaincopy
  1. XmppConnection.getInstance().login(username,password)  


希望對大家有所幫助~


發佈了12 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章