Xmpp的一些方法整理到一个工具类中了

XmppConnection.java

[java] view
plain
copy

[java] view
plain
copy

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

openfire Android学习(六)----总结的更多相关文章

  1. openfire Android学习(一)----实现用户注册、登录、修改密码和注销等

    以前学习过用Scoket 建立聊天,简单的建立聊天是没问题的,但如果要实现多人复杂的聊天,后台服务器代码就比较复杂,对于我这新手来讲就比较难了.后来在网上看到用openfire做服务器,利用强大的Sm ...

  2. openfire Android学习(三)----会议室创建、加入以及查询会议室中所有成员等

    openfire 中的会议室不像QQ群一样,不能保存那些离线用户,加入会议室后,一旦断开连接,就会离开会议室. 虽然如此,但如果要实现也不是不可能,我们可以自己做后台来保存,有兴趣的可以去试着实现一下 ...

  3. Android学习六:Socket 使用

    1socket的作用 通过http去获取服务器的数据在有些情况下是行不通的,所有使用socket与服务器通信也是必须掌握的 2.代码 好了上代码,代码中有解释,首先是简单的服务端代码 package ...

  4. android 学习六 构建用户界面和使用控件

    1.常用Android控件最终都会继承自View类 2.ViewGroup是一些布局类列表的基类,包括View和ViewGroup 3.构造界面的三种方法    a.完全使用代码(太灵活,而不好维护) ...

  5. Android学习六---OpenCV for android samples

    搭建好OpenCV4Android环境后,就要着手开发自己的应用了.对于一个没有OpenCV基础的人来开发OpenCV应用确实有点难度,不过我们可以从samples里学起,结合javadoc和万能的网 ...

  6. openfire Android学习(五)------连接断开重连

    首先要创建连接监听器,用来监听连接状态,这里我写了一个类 继承了ConnectionListener,重写了里面5个方法,最重要的两个方法connectionClosed()和connectionCl ...

  7. openfire Android学习(二)----对分组、好友和头像等一些操作

    一.查询所有分组 通过Roster来获取所有分组,Roster可以通过connection.getRoster()来得到. [java] view plaincopy /** * 获取所有组 * *  ...

  8. openfire Android学习---android客户端聊天开发之登录 和 注销登录

    一切就绪,新建一个android测试工程: 上网权限配置,界面绘制啥的,这里就不说了. 首先 导入一个smark包.这个是用来维护长连接的,也可以是asmark.我用的是asmark 先普及一些基本知 ...

  9. openfire Android 学习(四)----单人聊天和多人聊天(发送消息、接收消息)

    一.单人聊天 1)发送消息: 首先要获取一个聊天窗口,getConnection()为获取连接connection的方法,调用getFriendChat()获取 [java] view plainco ...

随机推荐

  1. apple苹果产品国行和港行的区别

    [iPhone国行和港行的区别]国行:耳机只能用在苹果设备上,不能用其它设备.充电器不用转接,直接可以用,保修的时候如果换新了,重新计算一年保修期.国行是三网通用.港行:耳机可以用在任何设备上.充电器 ...

  2. gdb调试手册 一 gdb概述

    一 gdb概述 gdb调试器的目的是让你了解其他的程序在执行的时候发生了什么或者其他程序崩溃时正在做什么 gdb主要能够在运行中做四类事情(包括这些事情中的一些附加的事情)来帮助你获取bugs a 运 ...

  3. Leetcode 416.分割等和子集

    分割等和子集 给定一个只包含正整数的非空数组.是否可以将这个数组分割成两个子集,使得两个子集的元素和相等. 注意: 每个数组中的元素不会超过 100 数组的大小不会超过 200 示例 1: 输入: [ ...

  4. POJ 1240 Pre-Post-erous!

    k叉树的前序和后续遍历,问一共有多少种这样的k叉树 这个就是树的同构,组合数就能解决 同样的题目在51nod也有的,我的另一篇博客 POJ 1240 Pre-Post-erous! We are al ...

  5. malloc&&free的系统运行机制及其源代码的理解

    一.malloc()和free()的基本概念以及基本用法: 1.函数原型及说明: void *malloc(long NumBytes):该函数分配了NumBytes个字节,并返回了指向这块内存的指针 ...

  6. DS作业06-图

    1.本周学习总结(0--2分) 1.1思维导图 1.2谈谈你对图结构的认识及学习体会. 图这一章的学习,是经过树学习后,难得一章重新寻找到感觉的学习.因为这一章比较少用递归,使用的是结构体,很多东西我 ...

  7. Unity3D - UGUI的初级应用

    添加字体: 把下载好的字体拖拽到Project面板中 - 点击Text组件中Text属性后面的圆点 - 选择刚刚拖拽的字体即可. 创建ToggleGroup(开关组): 1.在Canvas下创建两个T ...

  8. javascript图片放大镜效果展示

    javascript图片放大镜效果展示 <!DOCTYPE html> <html> <head lang="en"> <meta cha ...

  9. 刷题总结——coneology(poj2932 扫描线)

    题目: Description A student named Round Square loved to play with cones. He would arrange cones with d ...

  10. 算法复习——数位dp

    开头由于不知道讲啥依然搬讲义 对于引入的这个问题,讲义里已经很清楚了,我更喜欢用那个建树的理解···· 相当于先预处理f,然后从起点开始在树上走··记录目前已经找到了多少个满足题意的数k,如果枚举到第 ...