功能实现:注册,登录,单聊表情,文本,图片,语音的发送接收,添加好友,删除好友,查找好友,修改密码,消息提醒设置,获取离线消息等功能


1.前期准备

1.下载opnefire软件:https://www.igniterealtime.org/downloads/index.jsp

2.下载一款数据库软件:mysql

4.在AS中添加smack相关依赖包:

  1. compile 'org.igniterealtime.smack:smack-android-extensions:4.1.4'
  2. compile 'org.igniterealtime.smack:smack-tcp:4.1.4'
  3. compile 'org.igniterealtime.smack:smack-im:4.1.4'
  4. compile 'org.igniterealtime.smack:smack-extensions:4.1.4'
  5. compile 'com.rockerhieu.emojicon:library:1.3.3'

5.核心代码块:

  1.  

  1. XmppConnection 工具类

  1. import android.content.Context;
  2. import android.database.Cursor;
  3. import android.os.Environment;
  4. import android.text.TextUtils;
  5. import android.util.Log;
  6.  
  7. import org.jivesoftware.smack.AbstractXMPPConnection;
  8. import org.jivesoftware.smack.ConnectionConfiguration;
  9. import org.jivesoftware.smack.MessageListener;
  10. import org.jivesoftware.smack.SmackConfiguration;
  11. import org.jivesoftware.smack.SmackException;
  12. import org.jivesoftware.smack.XMPPException;
  13. import org.jivesoftware.smack.chat.Chat;
  14. import org.jivesoftware.smack.chat.ChatManager;
  15. import org.jivesoftware.smack.chat.ChatMessageListener;
  16. import org.jivesoftware.smack.packet.Message;
  17. import org.jivesoftware.smack.packet.Presence;
  18. import org.jivesoftware.smack.provider.ProviderManager;
  19. import org.jivesoftware.smack.roster.Roster;
  20. import org.jivesoftware.smack.roster.RosterEntry;
  21. import org.jivesoftware.smack.roster.RosterGroup;
  22. import org.jivesoftware.smack.tcp.XMPPTCPConnection;
  23. import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
  24. import org.jivesoftware.smackx.address.provider.MultipleAddressesProvider;
  25. import org.jivesoftware.smackx.bytestreams.ibb.provider.CloseIQProvider;
  26. import org.jivesoftware.smackx.bytestreams.ibb.provider.OpenIQProvider;
  27. import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;
  28. import org.jivesoftware.smackx.chatstates.packet.ChatStateExtension;
  29. import org.jivesoftware.smackx.commands.provider.AdHocCommandDataProvider;
  30. import org.jivesoftware.smackx.delay.provider.DelayInformationProvider;
  31. import org.jivesoftware.smackx.disco.provider.DiscoverInfoProvider;
  32. import org.jivesoftware.smackx.disco.provider.DiscoverItemsProvider;
  33. import org.jivesoftware.smackx.filetransfer.FileTransferListener;
  34. import org.jivesoftware.smackx.filetransfer.FileTransferManager;
  35. import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
  36. import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;
  37. import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
  38. import org.jivesoftware.smackx.iqlast.packet.LastActivity;
  39. import org.jivesoftware.smackx.iqprivate.PrivateDataManager;
  40. import org.jivesoftware.smackx.iqregister.AccountManager;
  41. import org.jivesoftware.smackx.muc.DiscussionHistory;
  42. import org.jivesoftware.smackx.muc.HostedRoom;
  43. import org.jivesoftware.smackx.muc.MultiUserChat;
  44. import org.jivesoftware.smackx.muc.MultiUserChatManager;
  45. import org.jivesoftware.smackx.muc.packet.GroupChatInvitation;
  46. import org.jivesoftware.smackx.muc.provider.MUCAdminProvider;
  47. import org.jivesoftware.smackx.muc.provider.MUCOwnerProvider;
  48. import org.jivesoftware.smackx.muc.provider.MUCUserProvider;
  49. import org.jivesoftware.smackx.offline.OfflineMessageManager;
  50. import org.jivesoftware.smackx.offline.packet.OfflineMessageInfo;
  51. import org.jivesoftware.smackx.offline.packet.OfflineMessageRequest;
  52. import org.jivesoftware.smackx.privacy.provider.PrivacyProvider;
  53. import org.jivesoftware.smackx.search.ReportedData;
  54. import org.jivesoftware.smackx.search.UserSearch;
  55. import org.jivesoftware.smackx.search.UserSearchManager;
  56. import org.jivesoftware.smackx.sharedgroups.packet.SharedGroupsInfo;
  57. import org.jivesoftware.smackx.si.provider.StreamInitiationProvider;
  58. import org.jivesoftware.smackx.vcardtemp.provider.VCardProvider;
  59. import org.jivesoftware.smackx.xdata.Form;
  60. import org.jivesoftware.smackx.xdata.FormField;
  61. import org.jivesoftware.smackx.xdata.provider.DataFormProvider;
  62. import org.jivesoftware.smackx.xhtmlim.provider.XHTMLExtensionProvider;
  63.  
  64. import java.io.BufferedInputStream;
  65. import java.io.BufferedReader;
  66. import java.io.File;
  67. import java.io.FileInputStream;
  68. import java.io.IOException;
  69. import java.io.InputStreamReader;
  70. import java.net.URL;
  71. import java.net.URLConnection;
  72. import java.util.ArrayList;
  73. import java.util.Collection;
  74. import java.util.Date;
  75. import java.util.HashMap;
  76. import java.util.Iterator;
  77. import java.util.List;
  78. import java.util.Map;
  79. import java.util.Set;
  80.  
  81. import cnpc.fcyt.fcydyy.util.LoggerUtil;
  82. import cnpc.fcyt.fcydyy.xmpp.bean.XmppChat;
  83. import cnpc.fcyt.fcydyy.xmpp.bean.XmppMessage;
  84. import cnpc.fcyt.fcydyy.xmpp.bean.XmppUser;
  85. import cnpc.fcyt.fcydyy.xmpp.dao.FriendChatDao;
  86. import cnpc.fcyt.fcydyy.xmpp.dao.MessageDao;
  87. import cnpc.fcyt.fcydyy.xmpp.util.TimeUtil;
  88. import cnpc.fcyt.fcydyy.xmpp.util.UserConstants;
  89.  
  90. /**
  91. * XmppConnection 工具类
  92. */
  93.  
  94. public class XmppConnection {
  95. private int SERVER_PORT = 5222;
  96. private String SERVER_HOST = "192.168.0.195";
  97. private String SERVER_NAME = "192.168.0.195";
  98. public AbstractXMPPConnection connection = null;
  99. private static XmppConnection xmppConnection = new XmppConnection();
  100. private XMConnectionListener connectionListener;
  101.  
  102. /**
  103. * 单例模式
  104. *
  105. * @return XmppConnection
  106. */
  107. public synchronized static XmppConnection getInstance() {
  108. configure(new ProviderManager());
  109. return xmppConnection;
  110. }
  111.  
  112. /**
  113. * 创建连接
  114. */
  115. public AbstractXMPPConnection getConnection() {
  116.  
  117. if (connection == null) {
  118. // 开线程打开连接,避免在主线程里面执行HTTP请求
  119. // Caused by: android.os.NetworkOnMainThreadException
  120. new Thread(new Runnable() {
  121. @Override
  122. public void run() {
  123. openConnection();
  124. }
  125. }).start();
  126. }
  127. return connection;
  128. }
  129.  
  130. public void setConnectionToNull() {
  131. connection = null;
  132. }
  133.  
  134. /**
  135. * 判断是否已连接
  136. */
  137. public boolean checkConnection() {
  138. return null != connection && connection.isConnected();
  139. }
  140.  
  141. /**
  142. * 打开连接
  143. */
  144. public boolean openConnection() {
  145. try {
  146. if (null == connection || !connection.isAuthenticated()) {
  147. SmackConfiguration.DEBUG = true;
  148. XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
  149. //设置openfire主机IP
  150. config.setHost(SERVER_HOST);
  151. //设置openfire服务器名称
  152. config.setServiceName(SERVER_NAME);
  153. //设置端口号:默认5222
  154. config.setPort(SERVER_PORT);
  155. //禁用SSL连接
  156. config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled).setCompressionEnabled(false);
  157. //设置Debug
  158. config.setDebuggerEnabled(true);
  159. //设置离线状态
  160. config.setSendPresence(false);
  161. //设置开启压缩,可以节省流量
  162. config.setCompressionEnabled(true);
  163.  
  164. //需要经过同意才可以添加好友
  165. Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.accept_all);
  166.  
  167. // 将相应机制隐掉
  168. //SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
  169. //SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
  170.  
  171. connection = new XMPPTCPConnection(config.build());
  172. connection.connect();// 连接到服务器
  173.  
  174. return true;
  175. }
  176. } catch (Exception xe) {
  177. xe.printStackTrace();
  178. connection = null;
  179. }
  180. return false;
  181. }
  182.  
  183. /**
  184. * 关闭连接
  185. */
  186. public void closeConnection() {
  187. if (connection != null) {
  188. // 移除连接监听
  189. connection.removeConnectionListener(connectionListener);
  190. if (connection.isConnected())
  191. connection.disconnect();
  192. connection = null;
  193. }
  194.  
  195. Log.i("XmppConnection", "关闭连接");
  196. }
  197.  
  198. /**
  199. * 删除好友
  200. *
  201. * @param
  202. */
  203. public boolean deleteRosterEntry(RosterEntry rosterEntry) {
  204. try {
  205. Roster.getInstanceFor(connection).removeEntry(rosterEntry);
  206. return true;
  207. } catch (Exception e) {
  208. e.printStackTrace();
  209. return false;
  210. }
  211. }
  212.  
  213. /**
  214. * 判断连接是否通过了身份验证
  215. * 即是否已登录
  216. *
  217. * @return
  218. */
  219. public boolean isAuthenticated() {
  220. return connection != null && connection.isConnected() && connection.isAuthenticated();
  221. }
  222.  
  223. /**
  224. * 添加好友 无分组
  225. *
  226. * @param userName userName
  227. * @param name name
  228. * @return boolean
  229. */
  230. public boolean addUser(String userName, String name) {
  231. if (getConnection() == null)
  232. return false;
  233. try {
  234.  
  235. Roster.getInstanceFor(connection).createEntry(userName, name, null);
  236.  
  237. return true;
  238. } catch (Exception e) {
  239. e.printStackTrace();
  240. return false;
  241. }
  242. }
  243.  
  244. /**
  245. * 获取账号的全部信息
  246. */
  247. public void getAccountAttributes() {
  248. try {
  249.  
  250. Set<String> accountAttributes = AccountManager.getInstance(connection).getAccountAttributes();
  251. Iterator<String> iterator = accountAttributes.iterator();
  252. while (iterator.hasNext()) {
  253. String trim = iterator.next().toString().trim();
  254. Log.e("Account", "获取账号信息成功===" + trim);
  255. }
  256. } catch (SmackException.NoResponseException e) {
  257. e.printStackTrace();
  258. Log.e("Account", "连接服务器失败");
  259. } catch (XMPPException.XMPPErrorException e) {
  260. e.printStackTrace();
  261. Log.e("Account", "该账户已存在");
  262. } catch (SmackException.NotConnectedException e) {
  263. e.printStackTrace();
  264. Log.e("Account", "服务器连接失败");
  265. }
  266. }
  267.  
  268. /**
  269. * 登录
  270. *
  271. * @param account 登录帐号
  272. * @param password 登录密码
  273. * @return true登录成功
  274. */
  275. public boolean login(String account, String password) {
  276. try {
  277. if (getConnection() == null)
  278. return false;
  279.  
  280. getConnection().login(account, password);
  281.  
  282. // 更改在线状态
  283. // setPresence(0);
  284.  
  285. // 添加连接监听
  286. connectionListener = new XMConnectionListener(account, password);
  287. getConnection().addConnectionListener(connectionListener);
  288. receivedFile();
  289. return true;
  290. } catch (Exception xe) {
  291. xe.printStackTrace();
  292. }
  293. return false;
  294. }
  295.  
  296. /**
  297. * 获取用户离线在线状态 1 在线 2 离线
  298. */
  299. public int getStatus(RosterEntry entry) {
  300. Roster roster = Roster.getInstanceFor(connection);
  301. Presence presence = roster.getPresence(entry.getUser() + UserConstants.chatDoMain);
  302.  
  303. LoggerUtil.systemOut(entry.getUser() + "用户名");
  304. LoggerUtil.systemOut(presence.getType().name() + "获取到的 类型状态");
  305. LoggerUtil.systemOut(presence.getType().toString() + "获取到的 类型状态");
  306. if (presence.getType() == Presence.Type.available) {
  307. return 1;//在线
  308. }
  309. return 2;//离线
  310. }
  311.  
  312. /**
  313. * 更改用户状态
  314. */
  315. public void setPresence(int code) {
  316. org.jivesoftware.smack.XMPPConnection con = getConnection();
  317. if (con == null)
  318. return;
  319. Presence presence;
  320. try {
  321. switch (code) {
  322. case 0:
  323. presence = new Presence(Presence.Type.available);
  324. con.sendStanza(presence);
  325. Log.v("state", "设置在线");
  326. break;
  327. case 1:
  328. presence = new Presence(Presence.Type.available);
  329. presence.setMode(Presence.Mode.chat);
  330. con.sendStanza(presence);
  331. Log.v("state", "设置Q我吧");
  332. break;
  333. case 2:
  334. presence = new Presence(Presence.Type.available);
  335. presence.setMode(Presence.Mode.dnd);
  336. con.sendStanza(presence);
  337. Log.v("state", "设置忙碌");
  338. break;
  339. case 3:
  340. presence = new Presence(Presence.Type.available);
  341. presence.setMode(Presence.Mode.away);
  342. con.sendStanza(presence);
  343. Log.v("state", "设置离开");
  344. break;
  345. case 4:
  346. // Roster roster = con.getRoster();
  347. // Collection<RosterEntry> entries = roster.getEntries();
  348. // for (RosterEntry entry : entries) {
  349. // presence = new Presence(Presence.Type.unavailable);
  350. // presence.setPacketID(Packet.ID_NOT_AVAILABLE);
  351. // presence.setFrom(con.getUser());
  352. // presence.setTo(entry.getUser());
  353. // con.sendPacket(presence);
  354. // Log.v("state", presence.toXML());
  355. // }
  356. // // 向同一用户的其他客户端发送隐身状态
  357. // presence = new Presence(Presence.Type.unavailable);
  358. // presence.setPacketID(Packet.ID_NOT_AVAILABLE);
  359. // presence.setFrom(con.getUser());
  360. // presence.setTo(StringUtils.parseBareAddress(con.getUser()));
  361. // con.sendStanza(presence);
  362. // Log.v("state", "设置隐身");
  363. // break;
  364. case 5:
  365. presence = new Presence(Presence.Type.unavailable);
  366. con.sendStanza(presence);
  367. Log.v("state", "设置离线");
  368. break;
  369. default:
  370. break;
  371. }
  372. } catch (Exception e) {
  373. e.printStackTrace();
  374. }
  375. }
  376.  
  377. /**
  378. * 获取所有组
  379. *
  380. * @return 所有组集合
  381. */
  382. public List<RosterGroup> getGroups() {
  383. if (getConnection() == null)
  384. return null;
  385. List<RosterGroup> groupList = new ArrayList<>();
  386. Collection<RosterGroup> rosterGroup = Roster.getInstanceFor(connection).getGroups();
  387. for (RosterGroup aRosterGroup : rosterGroup) {
  388. groupList.add(aRosterGroup);
  389. }
  390. return groupList;
  391. }
  392.  
  393. /**
  394. * 获取某个组里面的所有好友
  395. *
  396. * @param groupName 组名
  397. * @return List<RosterEntry>
  398. */
  399. public List<RosterEntry> getEntriesByGroup(String groupName) {
  400. if (getConnection() == null)
  401. return null;
  402. List<RosterEntry> EntriesList = new ArrayList<>();
  403. RosterGroup rosterGroup = Roster.getInstanceFor(connection).getGroup(groupName);
  404. Collection<RosterEntry> rosterEntry = rosterGroup.getEntries();
  405. for (RosterEntry aRosterEntry : rosterEntry) {
  406. EntriesList.add(aRosterEntry);
  407. }
  408. return EntriesList;
  409. }
  410.  
  411. /**
  412. * 获取所有好友信息
  413. *
  414. * @return List<RosterEntry>
  415. */
  416. public List<RosterEntry> getAllEntries() {
  417. if (getConnection() == null)
  418. return null;
  419. List<RosterEntry> Enlist = new ArrayList<>();
  420. Collection<RosterEntry> rosterEntry = Roster.getInstanceFor(connection).getEntries();
  421. for (RosterEntry aRosterEntry : rosterEntry) {
  422. Enlist.add(aRosterEntry);
  423. }
  424. return Enlist;
  425. }
  426.  
  427. /**
  428. * 添加一个分组
  429. *
  430. * @param groupName groupName
  431. * @return boolean
  432. */
  433. public boolean addGroup(String groupName) {
  434. if (getConnection() == null)
  435. return false;
  436. try {
  437. Roster.getInstanceFor(connection).createGroup(groupName);
  438. Log.v("addGroup", groupName + "創建成功");
  439. return true;
  440. } catch (Exception e) {
  441. e.printStackTrace();
  442. return false;
  443. }
  444. }
  445.  
  446. /**
  447. * 删除分组
  448. *
  449. * @param groupName groupName
  450. * @return boolean
  451. */
  452. public boolean removeGroup(String groupName) {
  453. return true;
  454. }
  455.  
  456. /**
  457. * 文件转字节
  458. *
  459. * @param file file
  460. * @return byte[]
  461. * @throws IOException
  462. */
  463. private byte[] getFileBytes(File file) throws IOException {
  464. BufferedInputStream bis = null;
  465. try {
  466. bis = new BufferedInputStream(new FileInputStream(file));
  467. int bytes = (int) file.length();
  468. byte[] buffer = new byte[bytes];
  469. int readBytes = bis.read(buffer);
  470. if (readBytes != buffer.length) {
  471. throw new IOException("Entire file not read");
  472. }
  473. return buffer;
  474. } finally {
  475. if (bis != null) {
  476. bis.close();
  477. }
  478. }
  479. }
  480.  
  481. /**
  482. * 发送群组聊天消息
  483. *
  484. * @param muc muc
  485. * @param message 消息文本
  486. */
  487. public void sendGroupMessage(MultiUserChat muc, String message) {
  488. try {
  489. muc.sendMessage(message);
  490. } catch (Exception e) {
  491. e.printStackTrace();
  492. }
  493. }
  494.  
  495. /**
  496. * 修改密码
  497. *
  498. * @return true成功
  499. */
  500. public boolean changePassword(String pwd) {
  501. if (getConnection() == null)
  502. return false;
  503. try {
  504. AccountManager.getInstance(connection).changePassword(pwd);
  505. return true;
  506. } catch (Exception e) {
  507. e.printStackTrace();
  508. return false;
  509. }
  510. }
  511.  
  512. /**
  513. * 创建群聊聊天室
  514. *
  515. * @param roomName 聊天室名字
  516. * @param nickName 创建者在聊天室中的昵称
  517. * @param password 聊天室密码
  518. * @return
  519. */
  520. public MultiUserChat createChatRoom(String roomName, String nickName, String password) {
  521. MultiUserChat muc;
  522. try {
  523. // 创建一个MultiUserChat
  524. muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(roomName + "@conference.192.168.0.195");
  525. // 创建聊天室
  526. boolean isCreated = muc.createOrJoin(nickName);
  527. if (isCreated) {
  528. // 获得聊天室的配置表单
  529. Form form = muc.getConfigurationForm();
  530. // 根据原始表单创建一个要提交的新表单。
  531. Form submitForm = form.createAnswerForm();
  532. // 向要提交的表单添加默认答复
  533. List<FormField> fields = form.getFields();
  534. for (int i = 0; fields != null && i < fields.size(); i++) {
  535. if (FormField.Type.hidden != fields.get(i).getType() &&
  536. fields.get(i).getVariable() != null) {
  537. // 设置默认值作为答复
  538. submitForm.setDefaultAnswer(fields.get(i).getVariable());
  539. }
  540. }
  541. // 设置聊天室的新拥有者
  542. List owners = new ArrayList();
  543. owners.add(connection.getUser());// 用户JID
  544. submitForm.setAnswer("muc#roomconfig_roomowners", owners);
  545. // 设置聊天室是持久聊天室,即将要被保存下来
  546. submitForm.setAnswer("muc#roomconfig_persistentroom", true);
  547. // 房间仅对成员开放
  548. submitForm.setAnswer("muc#roomconfig_membersonly", false);
  549. // 允许占有者邀请其他人
  550. submitForm.setAnswer("muc#roomconfig_allowinvites", true);
  551. if (password != null && password.length() != 0) {
  552. // 进入是否需要密码
  553. submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true);
  554. // 设置进入密码
  555. submitForm.setAnswer("muc#roomconfig_roomsecret", password);
  556. }
  557. // 能够发现占有者真实 JID 的角色
  558. // submitForm.setAnswer("muc#roomconfig_whois", "anyone");
  559. // 登录房间对话
  560. submitForm.setAnswer("muc#roomconfig_enablelogging", true);
  561. // 仅允许注册的昵称登录
  562. submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
  563. // 允许使用者修改昵称
  564. submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
  565. // 允许用户注册房间
  566. submitForm.setAnswer("x-muc#roomconfig_registration", false);
  567. // 发送已完成的表单(有默认值)到服务器来配置聊天室
  568. muc.sendConfigurationForm(submitForm);
  569.  
  570. } else {
  571.  
  572. }
  573. } catch (XMPPException | SmackException e) {
  574. e.printStackTrace();
  575.  
  576. return null;
  577. }
  578. return muc;
  579. }
  580. /**
  581. * 加入一个群聊聊天室
  582. *
  583. * @param jid 聊天室ip 格式为>>群组名称@conference.ip
  584. * @param nickName 用户在聊天室中的昵称
  585. * @param password 聊天室密码 没有密码则传""
  586. * @return
  587. */
  588. public MultiUserChat join(String jid, String nickName, String password) {
  589. try {
  590. // 使用XMPPConnection创建一个MultiUserChat窗口
  591. MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
  592. // 聊天室服务将会决定要接受的历史记录数量
  593. DiscussionHistory history = new DiscussionHistory();
  594. history.setMaxChars(0);
  595. // 用户加入聊天室
  596. muc.join(nickName, password);
  597. return muc;
  598. } catch (XMPPException | SmackException e) {
  599. e.printStackTrace();
  600. if ("XMPPError: not-authorized - auth".equals(e.getMessage())) {
  601. //需要密码加入
  602. }
  603. return null;
  604. }
  605. }
  606. /**
  607. * 获取服务器上的聊天室
  608. */
  609. public List<HostedRoom> getHostedRoom() {
  610. MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
  611. try {
  612. //serviceNames->conference.106.14.20.176
  613. List<String> serviceNames = manager.getServiceNames();
  614. for (int i = 0; i < serviceNames.size(); i++) {
  615. return manager.getHostedRooms(serviceNames.get(i));
  616. }
  617. } catch (Exception e) {
  618. e.printStackTrace();
  619. }
  620. return null;
  621. }
  622. /**
  623. * @param jid 格式为>>群组名称@conference.ip
  624. */
  625. private void initRoomListener(String jid) {
  626. MultiUserChat multiUserChat = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
  627. multiUserChat.addMessageListener(new MessageListener() {
  628. @Override
  629. public void processMessage(final Message message) {
  630. //当消息返回为空的时候,表示用户正在聊天窗口编辑信息并未发出消息
  631. if (!TextUtils.isEmpty(message.getBody())) {
  632. //收到的消息
  633. }
  634. }
  635. });
  636. //发送群聊消息
  637. // MultiUserChat multiUserChat = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
  638. // multiUserChat.sendMessage("Hello World");
  639.  
  640. }
  641.  
  642. // /**
  643. // * 创建房间
  644. // *
  645. // * @param roomName 房间名称
  646. // */
  647. // public MultiUserChat createRoom(String roomName, String password) {
  648. // if (getConnection() == null)
  649. // return null;
  650. //
  651. // MultiUserChat muc = null;
  652. // try {
  653. // // 创建一个MultiUserChat
  654. // muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(roomName+"@conference.192.168.0.195");
  655. // // 创建聊天室
  656. // muc.create(roomName);
  657. // // 获得聊天室的配置表单
  658. // Form form = muc.getConfigurationForm();
  659. // // 根据原始表单创建一个要提交的新表单。
  660. // Form submitForm = form.createAnswerForm();
  661. // // 向要提交的表单添加默认答复
  662. // for (FormField formField : form.getFields()) {
  663. // if (FormField.Type.hidden == formField.getType()
  664. // && formField.getVariable() != null) {
  665. // // 设置默认值作为答复
  666. // submitForm.setDefaultAnswer(formField.getVariable());
  667. // }
  668. // }
  669. // // 设置聊天室的新拥有者
  670. // List<String> owners = new ArrayList<>();
  671. // owners.add(getConnection().getUser());// 用户JID
  672. // submitForm.setAnswer("muc#roomconfig_roomowners", owners);
  673. // // 设置聊天室是持久聊天室,即将要被保存下来
  674. // submitForm.setAnswer("muc#roomconfig_persistentroom", true);
  675. // // 房间仅对成员开放
  676. // submitForm.setAnswer("muc#roomconfig_membersonly", false);
  677. // // 允许占有者邀请其他人
  678. // submitForm.setAnswer("muc#roomconfig_allowinvites", true);
  679. // if (!password.equals("")) {
  680. // // 进入是否需要密码
  681. // submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",
  682. // true);
  683. // // 设置进入密码
  684. // submitForm.setAnswer("muc#roomconfig_roomsecret", password);
  685. // }
  686. // // 能够发现占有者真实 JID 的角色
  687. // // submitForm.setAnswer("muc#roomconfig_whois", "anyone");
  688. // // 登录房间对话
  689. // submitForm.setAnswer("muc#roomconfig_enablelogging", true);
  690. // // 仅允许注册的昵称登录
  691. // submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
  692. // // 允许使用者修改昵称
  693. // submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
  694. // // 允许用户注册房间
  695. // submitForm.setAnswer("x-muc#roomconfig_registration", false);
  696. // // 发送已完成的表单(有默认值)到服务器来配置聊天室
  697. // muc.sendConfigurationForm(submitForm);
  698. // } catch (Exception e) {
  699. // e.printStackTrace();
  700. // LoggerUtil.systemOut(e.toString());
  701. // return null;
  702. // }
  703. // return muc;
  704. // }
  705.  
  706. /**
  707. * 加入会议室
  708. *
  709. * @param user 昵称
  710. * @param roomsName 会议室名
  711. */
  712. public MultiUserChat joinMultiUserChat(String user, String roomsName) {
  713. if (getConnection() == null)
  714. return null;
  715. try {
  716. // 使用XMPPConnection创建一个MultiUserChat窗口
  717. MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(connection.getServiceName());
  718.  
  719. // 用户加入聊天室
  720. muc.join(user);
  721.  
  722. Log.i("MultiUserChat", "会议室【" + roomsName + "】加入成功........");
  723. return muc;
  724. } catch (Exception e) {
  725. e.printStackTrace();
  726. Log.i("MultiUserChat", "会议室【" + roomsName + "】加入失败........");
  727. return null;
  728. }
  729. }
  730.  
  731. /**
  732. * 判断是否是好友
  733. *
  734. * @param
  735. * @param user
  736. * @return
  737. */
  738. public boolean isMyFriend(String user) {
  739.  
  740. List<RosterEntry> allEntries = XmppConnection.getInstance().getAllEntries();
  741. for (int i = 0; i < allEntries.size(); i++) {
  742. LoggerUtil.systemOut("allEntries.get(i).getUser() == " + allEntries.get(i).getUser());
  743. LoggerUtil.systemOut("user == " + user);
  744. if (allEntries.get(i).getUser().equals(user)) {
  745. LoggerUtil.systemOut(allEntries.get(i).getType().toString() + "type");
  746. if (allEntries.get(i).getType().toString().equals("both")) {
  747. return true;
  748. } else {
  749. return false;
  750. }
  751. }
  752. }
  753. return false;
  754.  
  755. }
  756. /**
  757. * 查询会议室成员名字
  758. *
  759. * @param muc
  760. */
  761. public List<String> findMulitUser(MultiUserChat muc) {
  762. if (getConnection() == null)
  763. return null;
  764. List<String> listUser = new ArrayList<>();
  765. List<String> occupants = muc.getOccupants();
  766. // 遍历出聊天室人员名称
  767. for (String entityFullJid : occupants) {
  768. // 聊天室成员名字
  769. String name = entityFullJid;
  770. listUser.add(name);
  771. }
  772. return listUser;
  773. }
  774.  
  775. /**
  776. * 判断OpenFire用户的状态 strUrl :
  777. * url格式 - http://my.openfire.com:9090/plugins/presence
  778. * /status?jid=user1@SERVER_NAME&type=xml
  779. * 返回值 : 0 - 用户不存在; 1 - 用户在线; 2 - 用户离线
  780. * 说明 :必须要求 OpenFire加载 presence 插件,同时设置任何人都可以访问
  781. */
  782. public int IsUserOnLine(String user) {
  783. String url = "http://" + SERVER_HOST + ":9090/plugins/presence/status?" +
  784. "jid=" + user;
  785. int shOnLineState = 0; // 不存在
  786. try {
  787. URL oUrl = new URL(url);
  788. URLConnection oConn = oUrl.openConnection();
  789. if (oConn != null) {
  790. BufferedReader oIn = new BufferedReader(new InputStreamReader(
  791. oConn.getInputStream()));
  792. String strFlag = oIn.readLine();
  793. oIn.close();
  794. System.out.println("strFlag" + strFlag);
  795. if (strFlag.contains("type=\"unavailable\"")) {
  796. shOnLineState = 2;
  797. }
  798. if (strFlag.contains("type=\"error\"")) {
  799. shOnLineState = 0;
  800. } else if (strFlag.contains("priority") || strFlag.contains("id=\"")) {
  801. shOnLineState = 1;
  802. }
  803. }
  804. } catch (Exception e) {
  805. e.printStackTrace();
  806. }
  807.  
  808. return shOnLineState;
  809. }
  810.  
  811. /**
  812. * 创建聊天窗口
  813. *
  814. * @param JID JID
  815. * @return Chat
  816. */
  817. public Chat getFriendChat(String JID, ChatMessageListener listener) {
  818. try {
  819. return ChatManager.getInstanceFor(XmppConnection.getInstance().getConnection())
  820. .createChat(JID, listener);
  821. } catch (Exception e) {
  822. e.printStackTrace();
  823. }
  824. return null;
  825. }
  826.  
  827. /**
  828. * 发送单人聊天消息
  829. *
  830. * @param chat chat
  831. * @param message 消息文本
  832. */
  833. public void sendSingleMessage(Chat chat, String message) {
  834. try {
  835. chat.sendMessage(message);
  836. } catch (SmackException.NotConnectedException e) {
  837. e.printStackTrace();
  838. }
  839. }
  840.  
  841. /**
  842. * 发消息
  843. *
  844. * @param chat chat
  845. * @param muc muc
  846. * @param message message
  847. */
  848. public void sendMessage(Chat chat, MultiUserChat muc, String message) {
  849. if (chat != null) {
  850. sendSingleMessage(chat, message);
  851. } else if (muc != null) {
  852. sendGroupMessage(muc, message);
  853. }
  854. }
  855.  
  856. /**
  857. * 获取离线消息
  858. *
  859. * @return
  860. */
  861. int i = 0;
  862.  
  863. public void getHisMessage(Context context) {
  864. LoggerUtil.systemOut("访问次数 " + (i++));
  865. setPresence(5);
  866. if (getConnection() == null)
  867. return;
  868.  
  869. try {
  870. OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection());
  871. List<Message> messageList = offlineManager.getMessages();
  872. int count = offlineManager.getMessageCount();
  873. LoggerUtil.systemOut("离线消息个数" + count);
  874. if (count <= 0) {
  875. setPresence(0);
  876. return;
  877. }
  878. for (Message message : messageList) {
  879. String[] send = message.getFrom().split("@");// 发送方
  880. String[] receiver = message.getTo().split("@");// 接收方
  881. saveofflineMessage(context, receiver[0], send[0], send[0], message.getBody(), "chat");
  882. saveofflineChatData(context, receiver[0], send[0], send[0], message.getBody());
  883.  
  884. }
  885. offlineManager.deleteMessages();
  886. } catch (Exception e) {
  887. e.printStackTrace();
  888. }
  889. setPresence(0);
  890. }
  891.  
  892. public boolean saveofflineMessage(Context context, String main, final String users, final String to, final String content, String type) {
  893.  
  894. Cursor cursor = MessageDao.getInstance(context).queryIshasResult(context, main, type);
  895.  
  896. if (cursor != null) {
  897. //更新
  898. if (type.equals("add")) {
  899. int result = cursor.getInt(cursor.getColumnIndex("result"));
  900. if (result == 0) {
  901. int id = cursor.getInt(cursor.getColumnIndex("id"));
  902. MessageDao.getInstance(context).update(context, id, content, 1);
  903. return true;
  904. } else {
  905. return false;
  906. }
  907. } else {
  908. int id = cursor.getInt(cursor.getColumnIndex("id"));
  909. MessageDao.getInstance(context).update(context, id, content, 1);
  910. return true;
  911. }
  912.  
  913. } else {
  914. //插入
  915. List<XmppUser> list1 = XmppConnection.getInstance().searchUsers(users);
  916. XmppMessage xm = new XmppMessage(to,
  917. type,
  918. new XmppUser(list1.get(0).getUserName(), list1.get(0).getName()),
  919. TimeUtil.getDate(),
  920. content,
  921. 1,
  922. main
  923. );
  924. LoggerUtil.systemOut("to" + to);
  925. MessageDao.getInstance(context).inserts(context, xm);
  926.  
  927. return true;
  928. }
  929.  
  930. }
  931.  
  932. public void saveofflineChatData(Context context, String main, final String users, final String to, final String content) {
  933. XmppChat xc = new XmppChat(main, users, "", "", 2, content, to, 1, new Date().getTime());
  934. FriendChatDao.getInstance(context).insert(context, xc);
  935. }
  936.  
  937. /**
  938. * 注册
  939. *
  940. * @param account 注册帐号
  941. * @param password 注册密码
  942. * @return 1、注册成功 0、注册失败
  943. */
  944. public boolean register(String account, String password, String nickName) {
  945. if (getConnection() == null)
  946. return false;
  947. try {
  948. // new
  949. Map<String, String> attributes = new HashMap<>();
  950. attributes.put("name", nickName);
  951. AccountManager.getInstance(connection).createAccount(account, password, attributes);
  952.  
  953. } catch (XMPPException | SmackException e) {
  954. e.printStackTrace();
  955. return false;
  956. }
  957.  
  958. return true;
  959. }
  960.  
  961. /**
  962. * 设置昵称
  963. *
  964. * @param
  965. * @param rosterEntry
  966. * @return
  967. */
  968. public boolean setNickName(RosterEntry rosterEntry, String nickName) {
  969. try {
  970. rosterEntry.setName(nickName);
  971. return true;
  972. } catch (SmackException.NotConnectedException e) {
  973. e.printStackTrace();
  974. return false;
  975. } catch (SmackException.NoResponseException e) {
  976. e.printStackTrace();
  977. return false;
  978. } catch (XMPPException.XMPPErrorException e) {
  979. e.printStackTrace();
  980. return false;
  981. }
  982. }
  983.  
  984. private OutgoingFileTransfer fileTransfer;
  985.  
  986. // 发送文件
  987. public void sendFile(String user, File file) throws Exception {
  988.  
  989. FileTransferManager instanceFor = FileTransferManager.getInstanceFor(connection);
  990.  
  991. fileTransfer = instanceFor.createOutgoingFileTransfer(user);
  992. fileTransfer.sendFile(file, "send file");
  993.  
  994. System.out.println("发送成功" + user + file.exists() + "文件路径" + file.getPath());
  995. }
  996.  
  997. /*
  998. * 语音接收文件监听接收文件
  999. *
  1000. * @author Administrator
  1001. *
  1002. */
  1003. private FileTransferListener mfiletransfransferlistener;//接受语音文件监听
  1004.  
  1005. public void receivedFile() {
  1006.  
  1007. // Create the file transfer manager
  1008.  
  1009. FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
  1010. mfiletransfransferlistener = new FileTransferListener() {
  1011. public void fileTransferRequest(FileTransferRequest request) {
  1012. // Check to see if the request should be accepted
  1013.  
  1014. LoggerUtil.systemOut("有文件接收了" + request.toString());
  1015. // Accept it
  1016. IncomingFileTransfer transfer = request.accept();
  1017. try {
  1018.  
  1019. File filePath = new File(Environment.getExternalStorageDirectory(), "fcyt");
  1020.  
  1021. if (!filePath.exists()) {
  1022. filePath.mkdirs();
  1023. }
  1024. // File file = new File( Environment
  1025. // .getExternalStorageDirectory()+"/fcyt/"
  1026. // +"/"+ request.getFileName());
  1027.  
  1028. String streamID = request.getStreamID();
  1029.  
  1030. LoggerUtil.systemOut("streamID", streamID);
  1031. File file = new File(filePath, request.getFileName());
  1032. System.out.println(request.getFileName() + "接收路径" + file.getPath() + "接收语音文件名称" + file.exists());
  1033.  
  1034. transfer.recieveFile(file);
  1035.  
  1036. } catch (Exception e) {
  1037. e.printStackTrace();
  1038. }
  1039.  
  1040. }
  1041. };
  1042.  
  1043. manager.addFileTransferListener(mfiletransfransferlistener);
  1044.  
  1045. }
  1046.  
  1047. /**
  1048. * 查找用户
  1049. *
  1050. * @param
  1051. * @param userName
  1052. * @return
  1053. */
  1054. public List<XmppUser> searchUsers(String userName) {
  1055. List<XmppUser> list = new ArrayList<XmppUser>();
  1056. UserSearchManager userSearchManager = new UserSearchManager(connection);
  1057. try {
  1058. Form searchForm = userSearchManager.getSearchForm("search."
  1059. + connection.getServiceName());
  1060. Form answerForm = searchForm.createAnswerForm();
  1061. answerForm.setAnswer("Username", true);
  1062. answerForm.setAnswer("Name", true);
  1063. answerForm.setAnswer("search", userName);
  1064. ReportedData data = userSearchManager.getSearchResults(answerForm, "search." + connection.getServiceName());
  1065. List<ReportedData.Row> rows = data.getRows();
  1066. for (ReportedData.Row row : rows) {
  1067. XmppUser user = new XmppUser(null, null);
  1068. user.setUserName(row.getValues("Username").toString().replace("]", "").replace("[", ""));
  1069. user.setName(row.getValues("Name").toString().replace("]", "").replace("[", ""));
  1070. list.add(user);
  1071. }
  1072.  
  1073. } catch (Exception e) {
  1074.  
  1075. }
  1076. return list;
  1077. }
  1078.  
  1079. public static void configure(ProviderManager pm) {
  1080.  
  1081. try {
  1082. Class.forName("org.jivesoftware.smack.ReconnectionManager");
  1083. } catch (Exception e) {
  1084. e.printStackTrace();
  1085. }
  1086.  
  1087. // Private Data Storage
  1088. pm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());
  1089.  
  1090. // Time
  1091. try {
  1092. pm.addIQProvider("query", "jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
  1093. } catch (ClassNotFoundException e) {
  1094. Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time");
  1095. }
  1096.  
  1097. // // Roster Exchange
  1098. // pm.addExtensionProvider("x", "jabber:x:roster", new RosterLoadedListener() {
  1099. // });
  1100. //
  1101. // // Message Events
  1102. // pm.addExtensionProvider("x", "jabber:x:event", new MessageEventProvider());
  1103.  
  1104. // Chat State
  1105. pm.addExtensionProvider("active", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  1106. pm.addExtensionProvider("composing", "http://jabber.org/protocol/chatstates",
  1107. new ChatStateExtension.Provider());
  1108. pm.addExtensionProvider("paused", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  1109. pm.addExtensionProvider("inactive", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  1110. pm.addExtensionProvider("gone", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
  1111.  
  1112. // XHTML
  1113. pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());
  1114.  
  1115. // Group Chat Invitations
  1116. pm.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());
  1117.  
  1118. // Service Discovery # Items
  1119. pm.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
  1120.  
  1121. // Service Discovery # Info
  1122. pm.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
  1123.  
  1124. // Data Forms
  1125. pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
  1126.  
  1127. // MUC User
  1128. pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());
  1129.  
  1130. // MUC Admin
  1131. pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
  1132.  
  1133. // MUC Owner
  1134. pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
  1135.  
  1136. // Delayed Delivery
  1137. pm.addExtensionProvider("x", "jabber:x:delay", new DelayInformationProvider());
  1138.  
  1139. // Version
  1140. try {
  1141. pm.addIQProvider("query", "jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
  1142. } catch (ClassNotFoundException e) {
  1143. // Not sure what's happening here.
  1144. }
  1145.  
  1146. // VCard
  1147. pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
  1148.  
  1149. // Offline Message Requests
  1150. pm.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
  1151.  
  1152. // Offline Message Indicator
  1153. pm.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
  1154.  
  1155. // Last Activity
  1156. pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());
  1157.  
  1158. // User Search
  1159. pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());
  1160.  
  1161. // SharedGroupsInfo
  1162. pm.addIQProvider("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup",
  1163. new SharedGroupsInfo.Provider());
  1164.  
  1165. // JEP-33: Extended Stanza Addressing
  1166. pm.addExtensionProvider("addresses", "http://jabber.org/protocol/address", new MultipleAddressesProvider());
  1167.  
  1168. // FileTransfer
  1169. pm.addIQProvider("si", "http://jabber.org/protocol/si", new StreamInitiationProvider());
  1170. pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
  1171. pm.addIQProvider("open", "http://jabber.org/protocol/ibb", new OpenIQProvider());
  1172. pm.addIQProvider("close", "http://jabber.org/protocol/ibb", new CloseIQProvider());
  1173. // pm.addExtensionProvider("data", "http://jabber.org/protocol/ibb", new DataPacketProvider());
  1174.  
  1175. // Privacy
  1176. pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
  1177. pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
  1178. pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands",
  1179. new AdHocCommandDataProvider.MalformedActionError());
  1180. pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands",
  1181. new AdHocCommandDataProvider.BadLocaleError());
  1182. pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands",
  1183. new AdHocCommandDataProvider.BadPayloadError());
  1184. pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands",
  1185. new AdHocCommandDataProvider.BadSessionIDError());
  1186. pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands",
  1187. new AdHocCommandDataProvider.SessionExpiredError());
  1188. }
  1189.  
  1190. }

XmppService后台监听接收消息


import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log; import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.StanzaListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Stanza; import java.util.Date;
import java.util.HashMap;
import java.util.List; import cnpc.fcyt.fcydyy.R;
import cnpc.fcyt.fcydyy.constant.ConfigConstants;
import cnpc.fcyt.fcydyy.event.LogoutEvent;
import cnpc.fcyt.fcydyy.event.RefreshChatMessageEvent;
import cnpc.fcyt.fcydyy.event.RefreshRedDotEvent;
import cnpc.fcyt.fcydyy.util.LoggerUtil;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppChat;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppMessage;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppUser;
import cnpc.fcyt.fcydyy.xmpp.dao.FriendChatDao;
import cnpc.fcyt.fcydyy.xmpp.dao.MessageDao;
import cnpc.fcyt.fcydyy.xmpp.util.SaveUserUtil;
import cnpc.fcyt.fcydyy.xmpp.util.TimeUtil;
import cnpc.fcyt.fcydyy.xmpp.util.UserConstants; public class XmppService extends Service { private XMPPConnection con;
public static ContentResolver resolver;
public static HashMap<String, Object> map;
String send[];//发送方
String receiver[];//接收方
public static String user;
public static SoundPool pool;
public static Vibrator vibrator;
Handler handler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
boolean authenticated = XmppConnection.getInstance().isAuthenticated(); AbstractXMPPConnection connection = XmppConnection.getInstance().getConnection();
if (connection!=null){
boolean connected = connection.isConnected();
if (!connected){
LoggerUtil.systemOut("IM服务器无法连接");
XmppConnection.getInstance().setConnectionToNull();
EventBus.getDefault().post(new LogoutEvent());
}else {
if (!authenticated) {
LoggerUtil.systemOut("掉线了"); EventBus.getDefault().post(new LogoutEvent());
}else {
LoggerUtil.systemOut("连接ing");
}
} } handler.sendEmptyMessageDelayed(1, 3000);
}
}
}; @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
resolver = getContentResolver();
map = new HashMap<>();
con = XmppConnection.getInstance().getConnection();
user = SaveUserUtil.loadAccount(XmppService.this).getUser();
pool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
pool.load(this, R.raw.tishi, 1);
vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
LoggerUtil.systemOut("启动服务......"); handler.sendEmptyMessageDelayed(1, 3000); } @Override
public IBinder onBind(Intent intent) {
return null;
} String messageID = ""; @Override
public int onStartCommand(Intent intent, int flags, int startId) {//'zS4Xw-62
if (null != con && con.isConnected()) { con.addAsyncStanzaListener(new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException { String stanzaId = packet.getStanzaId();
LoggerUtil.systemOut(stanzaId + "消息ID");
LoggerUtil.systemOut("messageID" + messageID);
if (messageID.equals(stanzaId) || stanzaId == null) { } else {
if (stanzaId != null) {
messageID = stanzaId;
} LoggerUtil.systemOut(packet.toString() + "通知来了");
if (packet instanceof Presence) {
Presence presence = (Presence) packet;
send = presence.getFrom().split("@");// 发送方
receiver = presence.getTo().split("@");// 接收方
// Presence.Type有7中状态
LoggerUtil.systemOut(presence.getType() + "信息类型");
if (presence.getType().equals(Presence.Type.subscribe)) {// 好友申请
LoggerUtil.systemOut(send[0] + "\t好友申请加为好友\t type="
+ presence.getType().toString()); sendBroad("add"); } else if (presence.getType().equals(Presence.Type.subscribed)) {// 同意添加好友
LoggerUtil.systemOut(send[0] + "\t同意添加好友\t type="
+ presence.getType().toString()); sendBroad("tongyi"); } else if (presence.getType().equals(Presence.Type.unsubscribe)) {// 删除好友
LoggerUtil.systemOut(send[0] + "\t删除好友\t type="
+ presence.getType().toString()); } else if (presence.getType().equals(Presence.Type.unsubscribed)) {// 拒绝对放的添加请求
LoggerUtil.systemOut(send[0] + "\t拒绝添加好友\t type="
+ presence.getType().toString()); sendBroad("jujue"); } else if (presence.getType().equals(Presence.Type.unavailable)) {// 好友下线
Log.i("service", send[0] + "\t 下线了");
LoggerUtil.systemOut(send[0] + "\t下线了\t type="
+ presence.getType().toString());
sendBroad("status", 6);
} else if (presence.getType().equals(Presence.Type.available)) {// 好友上线
//0.在线 1.Q我吧 2.忙碌 3.勿扰 4.离开 5.隐身 6.离线
if (presence.getMode() == Presence.Mode.chat) {//Q我吧
Log.i("service", send[0] + "\t 的状态改为了 Q我吧");
sendBroad("status", 1);
} else if (presence.getMode() == Presence.Mode.dnd) {//忙碌
Log.i("service", send[0] + "\t 的状态改为了 忙碌了");
sendBroad("status", 2);
} else if (presence.getMode() == Presence.Mode.xa) {//忙碌
Log.i("service", send[0] + "\t 的状态改为了 勿扰了");
sendBroad("status", 3);
} else if (presence.getMode() == Presence.Mode.away) {//离开
Log.i("service", send[0] + "\t 的状态改为了 离开了");
sendBroad("status", 4);
} else {
Log.i("service", send[0] + "\t 的状态改为了 上线了");
sendBroad("status", 0);
} }
} else if (packet instanceof Message) {
Message msg = (Message) packet;
EventBus.getDefault().post(new RefreshRedDotEvent());
int viewType;
if (msg.getBody() != null) {
if (msg.getBody().length() > 3 && msg.getBody().toString().substring(0, 4).equals("http")) {
viewType = 2;
} else {
viewType = 1;
}
XmppChat xc = new XmppChat(UserConstants.loginuser, packet.getFrom().replace(UserConstants.chatDoMain, ""), "", "", 2,
                      msg.getBody().toString(), packet.getFrom().replace(UserConstants.chatDoMain, ""), viewType, new Date().getTime());
FriendChatDao.getInstance(XmppService.this).insert(XmppService.this, xc); sendBroad("chat", xc);
}
}
} }
}, null); } return super.onStartCommand(intent, flags, startId);
} private void sendBroad(String type, XmppChat xc) {
Intent intent;
intent = new Intent("xmpp_receiver");
intent.putExtra("type", type);
intent.putExtra("chat", xc);
sendBroadcast(intent);
} private void sendBroad(String type, int status) {
map.put(send[0], status);
Intent intent;
intent = new Intent("xmpp_receiver");
intent.putExtra("type", type);
sendBroadcast(intent);
} private void sendBroad(String type) {
String str_content = "";
String str_type = "";
switch (type) {
case "add":
str_content = "请求加为好友";
str_type = "add";
break; case "tongyi":
str_content = "同意添加好友";
str_type = "tongyi";
break; case "jujue":
str_content = "拒绝添加好友";
str_type = "jujue";
break;
} LoggerUtil.systemOut(send[0] + "发送人");
LoggerUtil.systemOut(receiver[0] + "接收人");
if (msgDatas(receiver[0], send[0], send[0], str_content, str_type)) { if (pool != null && ConfigConstants.getSound(this)) {
pool.play(1, 1, 1, 0, 0, 1);
} if (vibrator != null && ConfigConstants.getShake(this)) {
vibrator.vibrate(500);
}
Intent intent;
intent = new Intent("xmpp_receiver");
intent.putExtra("type", type);
sendBroadcast(intent);
} } public boolean msgDatas(final String main, final String users, final String to, final String content, String type) { Cursor cursor = MessageDao.getInstance(this).queryIshasResult(this, main, type); if (cursor != null) {
//更新
if (type.equals("add")) {
int result = cursor.getInt(cursor.getColumnIndex("result"));
if (result == 0) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
MessageDao.getInstance(this).update(this, id, content, 1);
//刷新聊天页面
EventBus.getDefault().post(new RefreshChatMessageEvent());
return true;
} else {
return false;
}
} else {
int id = cursor.getInt(cursor.getColumnIndex("id"));
MessageDao.getInstance(this).update(this, id, content, 1);
//刷新聊天页面
EventBus.getDefault().post(new RefreshChatMessageEvent());
return true;
} } else {
//插入
List<XmppUser> list1 = XmppConnection.getInstance().searchUsers(users);
XmppMessage xm = new XmppMessage(to,
type,
new XmppUser(list1.get(0).getUserName(), list1.get(0).getName()),
TimeUtil.getDate(),
content,
1,
main
);
LoggerUtil.systemOut("to" + to);
MessageDao.getInstance(this).inserts(this, xm);
//刷新聊天页面
EventBus.getDefault().post(new RefreshChatMessageEvent());
return true;
}
} }

XmppReceiver消息广播处理消息

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.v4.app.NotificationCompat; import org.greenrobot.eventbus.EventBus; import java.util.List; import cnpc.fcyt.fcydyy.R;
import cnpc.fcyt.fcydyy.constant.ConfigConstants;
import cnpc.fcyt.fcydyy.event.RefreshChatMessageEvent;
import cnpc.fcyt.fcydyy.util.LoggerUtil;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppChat;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppMessage;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppUser;
import cnpc.fcyt.fcydyy.xmpp.dao.MessageDao;
import cnpc.fcyt.fcydyy.xmpp.util.TimeUtil; public class XmppReceiver extends BroadcastReceiver { updateActivity ua = null;
public NotificationManager manager = null;
Context context; public XmppReceiver(updateActivity ua) {
this.ua = ua;
} @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
String type = intent.getStringExtra("type");
if (type.equals("chat")) { LoggerUtil.systemOut("有新的接收消息");
XmppChat xc = (XmppChat) intent.getSerializableExtra("chat");
if (ChatActivity.ca != null) { LoggerUtil.systemOut(ChatActivity.ca.user + "当前聊天用户");
LoggerUtil.systemOut(xc.getUser() + "新信息的用户");
LoggerUtil.systemOut(xc.getToo() + "当前聊天用户too"); if ((ChatActivity.ca.user).equals(xc.getToo())) {
ua.update(xc);
}
chatDatas(xc.getMain(), xc.getUser(), xc.getToo(), xc.getContent()); } else { int num = chatData(xc.getMain(), xc.getUser(), xc.getToo(), xc.getContent());
if (XmppService.vibrator != null && ConfigConstants.getShake(context)) {
XmppService.vibrator.vibrate(500);
}
if (!isAppOnForeground(context)) { //在message界面更新信息
if (manager == null) {
manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Intent intent1 = new Intent(context, ChatActivity.class);
intent1.putExtra("user", xc.getUser());
PendingIntent pi = PendingIntent.getActivity(context, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT); List<XmppUser> xmppUsers = XmppConnection.getInstance().searchUsers(xc.getUser()); Notification notify = new Notification.Builder(context)
.setAutoCancel(true)
.setTicker("有新消息")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("来自" + xmppUsers.get(0).getName() + "的消息")
.setContentText(xc.getContent())
.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
.setWhen(System.currentTimeMillis())
.setNumber(num)
.setContentIntent(pi).build();
manager.notify(0, notify);
} else {
if (XmppService.pool != null && ConfigConstants.getSound(context)) {
XmppService.pool.play(1, 1, 1, 0, 0, 1);
}
} } }
ua.update(type);
} public interface updateActivity {
public void update(String type); public void update(XmppChat xc);
} public int chatData(final String main, final String users, final String to, final String content) {
Cursor cursor = MessageDao.getInstance(context).queryIshasResult(context, main, "chat");
if (cursor != null) {
//更新
int id = cursor.getInt(cursor.getColumnIndex("id"));
int result = cursor.getInt(cursor.getColumnIndex("result"));
MessageDao.getInstance(context).update(context, id, content, result + 1);
//刷新聊天页面
EventBus.getDefault().post(new RefreshChatMessageEvent());
return (result + 1);
} else {
//插入
List<XmppUser> list1 = XmppConnection.getInstance().searchUsers(users);
XmppMessage xm = new XmppMessage(to,
"chat",
new XmppUser(list1.get(0).getUserName(), list1.get(0).getName()),
TimeUtil.getDate(),
content,
1,
main
);
LoggerUtil.systemOut("to3" + to);
MessageDao.getInstance(context).inserts(context, xm);
//刷新聊天页面
EventBus.getDefault().post(new RefreshChatMessageEvent());
return 1;
} } public void chatDatas(final String main, final String users, final String to, final String content) { int id = MessageDao.getInstance(context).queryIshas(context, main, "chat");
if (id != -1) {
//更新
MessageDao.getInstance(context).update(context, id, content, 0); } else {
//插入
List<XmppUser> list1 = XmppConnection.getInstance().searchUsers(users);
XmppMessage xm = new XmppMessage(to,
"chat",
new XmppUser(list1.get(0).getUserName(), list1.get(0).getName()),
TimeUtil.getDate(),
content,
0,
main
);
LoggerUtil.systemOut("to1" + to);
MessageDao.getInstance(context).inserts(context, xm); }
//刷新聊天页面
EventBus.getDefault().post(new RefreshChatMessageEvent()); } public boolean isAppOnForeground(Context context) {
// Returns a list of application processes that are running on the
// device ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
String packageName = context.getApplicationContext().getPackageName(); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
if (appProcesses == null)
return false; for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
} }

本地数据库建立,用于储存历史消息记录等

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import cnpc.fcyt.fcydyy.util.LoggerUtil;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppChat; public class FriendChatDao {
private static FriendChatDao mInstance; public Context context; private FriendChatDao(Context ctx) {
this.context = ctx;
} public static FriendChatDao getInstance(Context ctx) {
//懒汉: 考虑线程安全问题, 两种方式: 1. 给方法加同步锁 synchronized, 效率低; 2. 给创建对象的代码块加同步锁
//读数据不会出现线程安全问题, 写数据会出现线程安全问题
//a, B, C
if (mInstance == null) {
//B, C
synchronized (FriendChatDao.class) {
//a
if (mInstance == null) {
mInstance = new FriendChatDao(ctx);
}
}
}
return mInstance;
} public boolean insert(Context context, XmppChat xc) {
boolean isSucceed = false;
// 1. 在内存中创建数据库帮助类的对象
FriendChatOpenHelper helper = new FriendChatOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase db = helper.getWritableDatabase(); /**
* table :表名
* nullColumnHack:
*/
ContentValues values = new ContentValues();
values.put("main", xc.getMain());
values.put("user", xc.getUser());
values.put("nickname", xc.getNickname());
values.put("icon", xc.getIcon());
values.put("type", xc.getType());
values.put("content", xc.getContent()); values.put("too", xc.getToo());
values.put("viewtype", xc.getViewType());
values.put("time", xc.getTime()); long id = db.insert("chat", null, values);
if (id == -1) {
LoggerUtil.systemOut("插入失败");
isSucceed = false;
} else {
LoggerUtil.systemOut("插入成功");
isSucceed = true;
}
// 释放资源
db.close();
return isSucceed;
} public ArrayList<XmppChat> query(Context context, String main, String too) {
// 1. 在内存中创建数据库帮助类的对象
FriendChatOpenHelper helper = new FriendChatOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getWritableDatabase();
Cursor cursor = database.query("chat", null, "too=?", new String[]{too}, null, null, null);
ArrayList<XmppChat> list = new ArrayList<>(); if (cursor != null) {
LoggerUtil.systemOut("查询个数 " + cursor.getCount());
while (cursor.moveToNext()) {
String user = cursor.getString(cursor.getColumnIndex("user"));
String nickname = cursor.getString(cursor.getColumnIndex("nickname"));
String icon = cursor.getString(cursor.getColumnIndex("icon"));
int type = cursor.getInt(cursor.getColumnIndex("type"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String times = cursor.getString(cursor.getColumnIndex("time"));
long time = Long.parseLong(times);
int viewType = cursor.getInt(cursor.getColumnIndex("viewtype"));
XmppChat xmppChat = new XmppChat(main, user, nickname, icon, type, content, too, viewType, time);
list.add(xmppChat);
} cursor.close();
}
database.close();
return list;
}
public boolean delete(Context context, String too) {
boolean isDelete = false;
// 1. 在内存中创建数据库帮助类的对象
FriendChatOpenHelper helper = new FriendChatOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getWritableDatabase();
int d = database.delete("chat", "too = ?", new String[]{too + ""});
if (d == 0) {
LoggerUtil.systemOut("删除失败");
isDelete = false;
} else {
LoggerUtil.systemOut("删除失败" + too);
isDelete = true;
}
// 释放资源
database.close();
return isDelete;
} }
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class FriendChatOpenHelper extends SQLiteOpenHelper {
private Context context;
public FriendChatOpenHelper(Context context) {
super(context, "XMPPChat.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table chat(id integer primary key autoincrement,main text,user text,nickname text,icon text,type integer,content text,too text,viewtype integer,time text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import cnpc.fcyt.fcydyy.util.LoggerUtil;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppUser;
import cnpc.fcyt.fcydyy.xmpp.bean.XmppMessage;
import cnpc.fcyt.fcydyy.xmpp.util.TimeUtil; public class MessageDao {
public Context context;
private static MessageDao mInstance; private MessageDao(Context ctx) {
this.context = ctx;
} public static MessageDao getInstance(Context ctx) {
//懒汉: 考虑线程安全问题, 两种方式: 1. 给方法加同步锁 synchronized, 效率低; 2. 给创建对象的代码块加同步锁
//读数据不会出现线程安全问题, 写数据会出现线程安全问题
//a, B, C
if (mInstance == null) {
//B, C
synchronized (MessageDao.class) {
//a
if (mInstance == null) {
mInstance = new MessageDao(ctx);
}
}
}
return mInstance;
} public List<XmppMessage> queryMessage(Context context,String main ) { // 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor = database.query("message", null, "main = ?", new String[]{main}, null, null, null);
ArrayList<XmppMessage> list = new ArrayList<>();
while (cursor.moveToNext()) {
String type = cursor.getString(cursor.getColumnIndex("type"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
String to = cursor.getString(cursor.getColumnIndex("too"));
String username = cursor.getString(cursor.getColumnIndex("username"));
String name = cursor.getString(cursor.getColumnIndex("name"));
XmppUser user = new XmppUser(username, name);
String time = cursor.getString(cursor.getColumnIndex("time"));
String content = cursor.getString(cursor.getColumnIndex("content"));
int result = cursor.getInt(cursor.getColumnIndex("result")); XmppMessage xm = new XmppMessage(id, to, type, user, time, content, result, main);
list.add(xm);
}
return list;
} public int queryIshas(Context context, String main, String type) { // 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor = database.query("message", null, "main=? and type=?", new String[]{main, type}, null, null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
//插入
LoggerUtil.systemOut("没有查询到");
return -1;
} else {
//更新
LoggerUtil.systemOut("查询到了");
int id = cursor.getInt(cursor.getColumnIndex("id"));
return id;
}
} else {
LoggerUtil.systemOut("cursor为空");
return -1;
}
}
public int queryhasMsg(Context context, String too, String type) { // 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor = database.query("message", null, "too=? and type=?", new String[]{too, type}, null, null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
//插入
LoggerUtil.systemOut("没有查询到");
return -1;
} else {
//更新
LoggerUtil.systemOut("查询到了");
int id = cursor.getInt(cursor.getColumnIndex("id"));
return id;
}
} else {
LoggerUtil.systemOut("cursor为空");
return -1;
}
} public Cursor queryIshasResult(Context context, String main, String type) { // 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getReadableDatabase();
Cursor cursor = database.query("message", null, "main=? and type=?", new String[]{main, type}, null, null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
//插入
LoggerUtil.systemOut("没有查询到");
return null;
} else {
//更新
LoggerUtil.systemOut("查询到了");
int result = cursor.getInt(cursor.getColumnIndex("result"));
return cursor;
}
} else {
LoggerUtil.systemOut("cursor为空");
return null;
}
} public boolean inserts(Context context, XmppMessage xm) {
boolean isSucceed = false;
// 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getWritableDatabase();
/**
* table :表名
* nullColumnHack:
*/
ContentValues values = new ContentValues();
values.put("main", xm.getMain());
values.put("name", xm.getUser().getName());
values.put("username", xm.getUser().getUserName());
values.put("too", xm.getTo());
values.put("type", xm.getType());
values.put("content", xm.getContent());
values.put("time", xm.getTime());
values.put("result", xm.getResult()); long id = database.insert("message", null, values);
if (id == -1) {
LoggerUtil.systemOut("插入失败");
isSucceed = false;
} else {
LoggerUtil.systemOut("插入成功");
isSucceed = true;
}
// 释放资源
database.close();
return isSucceed;
} public boolean update(Context context, int id, String content, int result) { // 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getWritableDatabase();
/**
* table :表名
* nullColumnHack:
*/
ContentValues values = new ContentValues();
values.put("content", content);
values.put("time", TimeUtil.getDate());
values.put("result", result); //返回更新的行数
int update = database.update("message", values, "id=?", new String[]{id + ""});
database.close();
return update > 0; }
public boolean updateResult(Context context, String too,String type ,String content) { // 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getWritableDatabase();
/**
* table :表名
* nullColumnHack:
*/
ContentValues values = new ContentValues();
values.put("result", 0);
if (!content.isEmpty()){
values.put("content", content);
} values.put("time", TimeUtil.getDate());
//返回更新的行数
int update = database.update("message", values, "too=? and type = ? ", new String[]{too,type});
database.close();
return update > 0;
}
public boolean delete(Context context, int id) {
boolean isDelete = false;
// 1. 在内存中创建数据库帮助类的对象
MessageOpenHelper helper = new MessageOpenHelper(context);
// 2. 在磁盘上创建数据库文件
SQLiteDatabase database = helper.getWritableDatabase();
int d = database.delete("message", "id = ?", new String[]{id + ""});
if (d == 0) {
LoggerUtil.systemOut("删除失败");
isDelete = false;
} else {
LoggerUtil.systemOut("删除失败" + id);
isDelete = true;
}
// 释放资源
database.close();
return isDelete;
}
}
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; public class MessageOpenHelper extends SQLiteOpenHelper { private Context context;
public MessageOpenHelper(Context context) {
super(context, "XMPPMessage.db",null,1); } @Override
public void onCreate(SQLiteDatabase db) { db.execSQL("create table message(id integer primary key autoincrement,main text,too text,name varchar(20),username text,type text,content text,time text,result integer)");
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}

6.开发过程中,注意注册的用户名和聊天等相关JID的区别,聊天发送的JID需要后缀标识,建群同理,无法与注册用户的JID对应,这点比较无语....


7.项目demo地址下载:https://download.csdn.net/download/jcf0706/10787309


欢迎大家下载学习,对于上面6有啥的好的解决办法,欢迎大家评论或者发邮箱给我建议jcf0706@163.com,一起学习进步!!!


用xmmp+openfire+smack搭建简易IM实现的更多相关文章

  1. openfire+asmack搭建的安卓即时通讯(一) 15.4.7

    最进开始做一些android的项目,除了一个新闻客户端的搭建,还需要一个实现一个即时通讯的功能,参考了很多大神成型的实例,了解到operfire+asmack是搭建简易即时通讯比较方便,所以就写了这篇 ...

  2. xmpp openfire smack 介绍和openfire安装及使用

    前言 Java领域的即时通信的解决方案可以考虑openfire+spark+smack.当然也有其他的选择. Openfire是基于Jabber协议(XMPP)实现的即时通信服务器端版本,目前建议使用 ...

  3. 使用ruby搭建简易的http服务和sass环境

    使用ruby搭建简易的http服务和sass环境 由于在通常的前端开发情况下,我们会有可能需要一个http服务,当然你可以选择自己写一个node的http服务,也比较简单,比如下面的node代码: v ...

  4. Django搭建简易博客

    Django简易博客,主要实现了以下功能 连接数据库 创建超级用户与后台管理 利用django-admin-bootstrap美化界面 template,view与动态URL 多说评论功能 Markd ...

  5. 基于xmpp openfire smack开发之Android客户端开发[3]

    在上两篇文章中,我们依次介绍openfire部署以及smack常用API的使用,这一节中我们着力介绍如何基于asmack开发一个Android的客户端,本篇的重点在实践,讲解和原理环节,大家可以参考前 ...

  6. EditPlus+MinGW搭建简易的C/C++开发环境

    EditPlus+MinGW搭建简易的C/C++开发环境 有时候想用C编点小程序,但是每次都要启动那难用又难看的VC实在是不情愿,而且老是会生成很多没用的中间文件,很讨厌,后来看到网上有很多人用Edi ...

  7. Python中使用Flask、MongoDB搭建简易图片服务器

    主要介绍了Python中使用Flask.MongoDB搭建简易图片服务器,本文是一个详细完整的教程,需要的朋友可以参考下 1.前期准备 通过 pip 或 easy_install 安装了 pymong ...

  8. express搭建简易web的服务器

    express搭建简易web的服务器 说到express我们就会想到nodejs,应为它是一款基于nodejs平台的web应用开发框架.既然它是基于nodejs平台的框架那么就得先安装nodejs. ...

  9. openfire+smack 实现即时通讯基本框架

    smack jar下载地址 http://www.igniterealtime.org/downloads/download-landing.jsp?file=smack/smack_3_2_2.zi ...

随机推荐

  1. CentOS7 SVN基本配置

    开机自启指令如下 systemctl enable svnserve.service 对应可执行脚本文件路径 vim /etc/sysconfig/svnserve 查看状态: ps -ef|grep ...

  2. RT-Thread中的串口DMA分析

    这里分析一下RT-Thread中串口DMA方式的实现,以供做新处理器串口支持时的参考. 背景 在如今的芯片性能和外设强大功能的情况下,串口不实现DMA/中断方式操作,我认为在实际项目中基本是不可接受的 ...

  3. python-迭代器与生成器3

    python-迭代器与生成器3 迭代器可以直接作用于for循环的数据类型有以下几种: 一类是集合数据类型,如list.tuple.dict.set.str等: 一类是generator,包括生成器和带 ...

  4. 浙大数据结构课后习题 练习二 7-3 Pop Sequence (25 分)

    Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and p ...

  5. Highcharts动态获取值

    <script type="text/javascript">         $(document).ready(function (){         var o ...

  6. 高性能mysql 第10章 复制

    复制功能不仅能够构建高可用的应用,同时也是高可用性,可扩展性,灾难恢复,备份以及数据仓库等工作的基础. mysql支持两种复制方式:基于语句的复制和基于行的复制.基于语句的复制(也成为逻辑复制)是早期 ...

  7. 我说CMMI之一:CMMI是什么--转载

    我说CMMI之一:CMMI是什么 有些朋友没有接触过CMMI,正在学习CMMI,CMMI本身的描述比较抽象,所以,读起来有些费劲.有些朋友实施过CMMI,但是可能存在对CMMI的一些误解,因此我想说说 ...

  8. k8s管理pod资源对象(下)

    一.标签与标签选择器 1.标签是k8s极具特色的功能之一,它能够附加于k8s的任何资源对象之上.简单来说,标签就是键值类型的数据,它们可于资源创建时直接指定,也可随时按需添加于活动对象中,而后即可由标 ...

  9. ToolStrip 选中某一项打勾

    (sender as ToolStripMenuItem).Checked = !(sender as ToolStripMenuItem).Checked;

  10. 【C#-算法】根据生日自动计算年龄_DataTime 的 DateDiff 方法

    dateTimePicker1.Value出生日期控件的值 long BirthDay = DateAndTime.DateDiff(DateInterval.Year, dateTimePicker ...