用xmmp+openfire+smack搭建简易IM实现
功能实现:注册,登录,单聊表情,文本,图片,语音的发送接收,添加好友,删除好友,查找好友,修改密码,消息提醒设置,获取离线消息等功能
1.前期准备
1.下载opnefire软件:https://www.igniterealtime.org/downloads/index.jsp
2.下载一款数据库软件:mysql
4.在AS中添加smack相关依赖包:
- compile 'org.igniterealtime.smack:smack-android-extensions:4.1.4'
- compile 'org.igniterealtime.smack:smack-tcp:4.1.4'
- compile 'org.igniterealtime.smack:smack-im:4.1.4'
- compile 'org.igniterealtime.smack:smack-extensions:4.1.4'
- compile 'com.rockerhieu.emojicon:library:1.3.3'
5.核心代码块:
- XmppConnection 工具类
- import android.content.Context;
- import android.database.Cursor;
- import android.os.Environment;
- import android.text.TextUtils;
- import android.util.Log;
- import org.jivesoftware.smack.AbstractXMPPConnection;
- import org.jivesoftware.smack.ConnectionConfiguration;
- import org.jivesoftware.smack.MessageListener;
- import org.jivesoftware.smack.SmackConfiguration;
- import org.jivesoftware.smack.SmackException;
- import org.jivesoftware.smack.XMPPException;
- import org.jivesoftware.smack.chat.Chat;
- import org.jivesoftware.smack.chat.ChatManager;
- import org.jivesoftware.smack.chat.ChatMessageListener;
- import org.jivesoftware.smack.packet.Message;
- import org.jivesoftware.smack.packet.Presence;
- import org.jivesoftware.smack.provider.ProviderManager;
- import org.jivesoftware.smack.roster.Roster;
- import org.jivesoftware.smack.roster.RosterEntry;
- import org.jivesoftware.smack.roster.RosterGroup;
- import org.jivesoftware.smack.tcp.XMPPTCPConnection;
- import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
- import org.jivesoftware.smackx.address.provider.MultipleAddressesProvider;
- import org.jivesoftware.smackx.bytestreams.ibb.provider.CloseIQProvider;
- import org.jivesoftware.smackx.bytestreams.ibb.provider.OpenIQProvider;
- import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;
- import org.jivesoftware.smackx.chatstates.packet.ChatStateExtension;
- import org.jivesoftware.smackx.commands.provider.AdHocCommandDataProvider;
- import org.jivesoftware.smackx.delay.provider.DelayInformationProvider;
- import org.jivesoftware.smackx.disco.provider.DiscoverInfoProvider;
- import org.jivesoftware.smackx.disco.provider.DiscoverItemsProvider;
- import org.jivesoftware.smackx.filetransfer.FileTransferListener;
- import org.jivesoftware.smackx.filetransfer.FileTransferManager;
- import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
- import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;
- import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;
- import org.jivesoftware.smackx.iqlast.packet.LastActivity;
- import org.jivesoftware.smackx.iqprivate.PrivateDataManager;
- import org.jivesoftware.smackx.iqregister.AccountManager;
- import org.jivesoftware.smackx.muc.DiscussionHistory;
- import org.jivesoftware.smackx.muc.HostedRoom;
- import org.jivesoftware.smackx.muc.MultiUserChat;
- import org.jivesoftware.smackx.muc.MultiUserChatManager;
- import org.jivesoftware.smackx.muc.packet.GroupChatInvitation;
- import org.jivesoftware.smackx.muc.provider.MUCAdminProvider;
- import org.jivesoftware.smackx.muc.provider.MUCOwnerProvider;
- import org.jivesoftware.smackx.muc.provider.MUCUserProvider;
- import org.jivesoftware.smackx.offline.OfflineMessageManager;
- import org.jivesoftware.smackx.offline.packet.OfflineMessageInfo;
- import org.jivesoftware.smackx.offline.packet.OfflineMessageRequest;
- import org.jivesoftware.smackx.privacy.provider.PrivacyProvider;
- import org.jivesoftware.smackx.search.ReportedData;
- import org.jivesoftware.smackx.search.UserSearch;
- import org.jivesoftware.smackx.search.UserSearchManager;
- import org.jivesoftware.smackx.sharedgroups.packet.SharedGroupsInfo;
- import org.jivesoftware.smackx.si.provider.StreamInitiationProvider;
- import org.jivesoftware.smackx.vcardtemp.provider.VCardProvider;
- import org.jivesoftware.smackx.xdata.Form;
- import org.jivesoftware.smackx.xdata.FormField;
- import org.jivesoftware.smackx.xdata.provider.DataFormProvider;
- import org.jivesoftware.smackx.xhtmlim.provider.XHTMLExtensionProvider;
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- 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.TimeUtil;
- import cnpc.fcyt.fcydyy.xmpp.util.UserConstants;
- /**
- * XmppConnection 工具类
- */
- public class XmppConnection {
- private int SERVER_PORT = 5222;
- private String SERVER_HOST = "192.168.0.195";
- private String SERVER_NAME = "192.168.0.195";
- public AbstractXMPPConnection connection = null;
- private static XmppConnection xmppConnection = new XmppConnection();
- private XMConnectionListener connectionListener;
- /**
- * 单例模式
- *
- * @return XmppConnection
- */
- public synchronized static XmppConnection getInstance() {
- configure(new ProviderManager());
- return xmppConnection;
- }
- /**
- * 创建连接
- */
- public AbstractXMPPConnection getConnection() {
- if (connection == null) {
- // 开线程打开连接,避免在主线程里面执行HTTP请求
- // Caused by: android.os.NetworkOnMainThreadException
- new Thread(new Runnable() {
- @Override
- public void run() {
- openConnection();
- }
- }).start();
- }
- return connection;
- }
- public void setConnectionToNull() {
- connection = null;
- }
- /**
- * 判断是否已连接
- */
- public boolean checkConnection() {
- return null != connection && connection.isConnected();
- }
- /**
- * 打开连接
- */
- public boolean openConnection() {
- try {
- if (null == connection || !connection.isAuthenticated()) {
- SmackConfiguration.DEBUG = true;
- XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
- //设置openfire主机IP
- config.setHost(SERVER_HOST);
- //设置openfire服务器名称
- config.setServiceName(SERVER_NAME);
- //设置端口号:默认5222
- config.setPort(SERVER_PORT);
- //禁用SSL连接
- config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled).setCompressionEnabled(false);
- //设置Debug
- config.setDebuggerEnabled(true);
- //设置离线状态
- config.setSendPresence(false);
- //设置开启压缩,可以节省流量
- config.setCompressionEnabled(true);
- //需要经过同意才可以添加好友
- Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.accept_all);
- // 将相应机制隐掉
- //SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
- //SASLAuthentication.blacklistSASLMechanism("DIGEST-MD5");
- connection = new XMPPTCPConnection(config.build());
- connection.connect();// 连接到服务器
- return true;
- }
- } catch (Exception xe) {
- xe.printStackTrace();
- connection = null;
- }
- return false;
- }
- /**
- * 关闭连接
- */
- public void closeConnection() {
- if (connection != null) {
- // 移除连接监听
- connection.removeConnectionListener(connectionListener);
- if (connection.isConnected())
- connection.disconnect();
- connection = null;
- }
- Log.i("XmppConnection", "关闭连接");
- }
- /**
- * 删除好友
- *
- * @param
- */
- public boolean deleteRosterEntry(RosterEntry rosterEntry) {
- try {
- Roster.getInstanceFor(connection).removeEntry(rosterEntry);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * 判断连接是否通过了身份验证
- * 即是否已登录
- *
- * @return
- */
- public boolean isAuthenticated() {
- return connection != null && connection.isConnected() && connection.isAuthenticated();
- }
- /**
- * 添加好友 无分组
- *
- * @param userName userName
- * @param name name
- * @return boolean
- */
- public boolean addUser(String userName, String name) {
- if (getConnection() == null)
- return false;
- try {
- Roster.getInstanceFor(connection).createEntry(userName, name, null);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * 获取账号的全部信息
- */
- public void getAccountAttributes() {
- try {
- Set<String> accountAttributes = AccountManager.getInstance(connection).getAccountAttributes();
- Iterator<String> iterator = accountAttributes.iterator();
- while (iterator.hasNext()) {
- String trim = iterator.next().toString().trim();
- Log.e("Account", "获取账号信息成功===" + trim);
- }
- } catch (SmackException.NoResponseException e) {
- e.printStackTrace();
- Log.e("Account", "连接服务器失败");
- } catch (XMPPException.XMPPErrorException e) {
- e.printStackTrace();
- Log.e("Account", "该账户已存在");
- } catch (SmackException.NotConnectedException e) {
- e.printStackTrace();
- Log.e("Account", "服务器连接失败");
- }
- }
- /**
- * 登录
- *
- * @param account 登录帐号
- * @param password 登录密码
- * @return true登录成功
- */
- public boolean login(String account, String password) {
- try {
- if (getConnection() == null)
- return false;
- getConnection().login(account, password);
- // 更改在线状态
- // setPresence(0);
- // 添加连接监听
- connectionListener = new XMConnectionListener(account, password);
- getConnection().addConnectionListener(connectionListener);
- receivedFile();
- return true;
- } catch (Exception xe) {
- xe.printStackTrace();
- }
- return false;
- }
- /**
- * 获取用户离线在线状态 1 在线 2 离线
- */
- public int getStatus(RosterEntry entry) {
- Roster roster = Roster.getInstanceFor(connection);
- Presence presence = roster.getPresence(entry.getUser() + UserConstants.chatDoMain);
- LoggerUtil.systemOut(entry.getUser() + "用户名");
- LoggerUtil.systemOut(presence.getType().name() + "获取到的 类型状态");
- LoggerUtil.systemOut(presence.getType().toString() + "获取到的 类型状态");
- if (presence.getType() == Presence.Type.available) {
- return 1;//在线
- }
- return 2;//离线
- }
- /**
- * 更改用户状态
- */
- public void setPresence(int code) {
- org.jivesoftware.smack.XMPPConnection con = getConnection();
- if (con == null)
- return;
- Presence presence;
- try {
- switch (code) {
- case 0:
- presence = new Presence(Presence.Type.available);
- con.sendStanza(presence);
- Log.v("state", "设置在线");
- break;
- case 1:
- presence = new Presence(Presence.Type.available);
- presence.setMode(Presence.Mode.chat);
- con.sendStanza(presence);
- Log.v("state", "设置Q我吧");
- break;
- case 2:
- presence = new Presence(Presence.Type.available);
- presence.setMode(Presence.Mode.dnd);
- con.sendStanza(presence);
- Log.v("state", "设置忙碌");
- break;
- case 3:
- presence = new Presence(Presence.Type.available);
- presence.setMode(Presence.Mode.away);
- con.sendStanza(presence);
- Log.v("state", "设置离开");
- break;
- case 4:
- // Roster roster = con.getRoster();
- // Collection<RosterEntry> entries = roster.getEntries();
- // for (RosterEntry entry : entries) {
- // presence = new Presence(Presence.Type.unavailable);
- // presence.setPacketID(Packet.ID_NOT_AVAILABLE);
- // presence.setFrom(con.getUser());
- // presence.setTo(entry.getUser());
- // con.sendPacket(presence);
- // Log.v("state", presence.toXML());
- // }
- // // 向同一用户的其他客户端发送隐身状态
- // presence = new Presence(Presence.Type.unavailable);
- // presence.setPacketID(Packet.ID_NOT_AVAILABLE);
- // presence.setFrom(con.getUser());
- // presence.setTo(StringUtils.parseBareAddress(con.getUser()));
- // con.sendStanza(presence);
- // Log.v("state", "设置隐身");
- // break;
- case 5:
- presence = new Presence(Presence.Type.unavailable);
- con.sendStanza(presence);
- Log.v("state", "设置离线");
- break;
- default:
- break;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 获取所有组
- *
- * @return 所有组集合
- */
- public List<RosterGroup> getGroups() {
- if (getConnection() == null)
- return null;
- List<RosterGroup> groupList = new ArrayList<>();
- Collection<RosterGroup> rosterGroup = Roster.getInstanceFor(connection).getGroups();
- for (RosterGroup aRosterGroup : rosterGroup) {
- groupList.add(aRosterGroup);
- }
- return groupList;
- }
- /**
- * 获取某个组里面的所有好友
- *
- * @param groupName 组名
- * @return List<RosterEntry>
- */
- public List<RosterEntry> getEntriesByGroup(String groupName) {
- if (getConnection() == null)
- return null;
- List<RosterEntry> EntriesList = new ArrayList<>();
- RosterGroup rosterGroup = Roster.getInstanceFor(connection).getGroup(groupName);
- Collection<RosterEntry> rosterEntry = rosterGroup.getEntries();
- for (RosterEntry aRosterEntry : rosterEntry) {
- EntriesList.add(aRosterEntry);
- }
- return EntriesList;
- }
- /**
- * 获取所有好友信息
- *
- * @return List<RosterEntry>
- */
- public List<RosterEntry> getAllEntries() {
- if (getConnection() == null)
- return null;
- List<RosterEntry> Enlist = new ArrayList<>();
- Collection<RosterEntry> rosterEntry = Roster.getInstanceFor(connection).getEntries();
- for (RosterEntry aRosterEntry : rosterEntry) {
- Enlist.add(aRosterEntry);
- }
- return Enlist;
- }
- /**
- * 添加一个分组
- *
- * @param groupName groupName
- * @return boolean
- */
- public boolean addGroup(String groupName) {
- if (getConnection() == null)
- return false;
- try {
- Roster.getInstanceFor(connection).createGroup(groupName);
- Log.v("addGroup", groupName + "創建成功");
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * 删除分组
- *
- * @param groupName groupName
- * @return boolean
- */
- public boolean removeGroup(String groupName) {
- return true;
- }
- /**
- * 文件转字节
- *
- * @param file file
- * @return byte[]
- * @throws IOException
- */
- private byte[] getFileBytes(File file) throws IOException {
- BufferedInputStream bis = null;
- try {
- bis = new BufferedInputStream(new FileInputStream(file));
- int bytes = (int) file.length();
- byte[] buffer = new byte[bytes];
- int readBytes = bis.read(buffer);
- if (readBytes != buffer.length) {
- throw new IOException("Entire file not read");
- }
- return buffer;
- } finally {
- if (bis != null) {
- bis.close();
- }
- }
- }
- /**
- * 发送群组聊天消息
- *
- * @param muc muc
- * @param message 消息文本
- */
- public void sendGroupMessage(MultiUserChat muc, String message) {
- try {
- muc.sendMessage(message);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 修改密码
- *
- * @return true成功
- */
- public boolean changePassword(String pwd) {
- if (getConnection() == null)
- return false;
- try {
- AccountManager.getInstance(connection).changePassword(pwd);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- /**
- * 创建群聊聊天室
- *
- * @param roomName 聊天室名字
- * @param nickName 创建者在聊天室中的昵称
- * @param password 聊天室密码
- * @return
- */
- public MultiUserChat createChatRoom(String roomName, String nickName, String password) {
- MultiUserChat muc;
- try {
- // 创建一个MultiUserChat
- muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(roomName + "@conference.192.168.0.195");
- // 创建聊天室
- boolean isCreated = muc.createOrJoin(nickName);
- if (isCreated) {
- // 获得聊天室的配置表单
- Form form = muc.getConfigurationForm();
- // 根据原始表单创建一个要提交的新表单。
- Form submitForm = form.createAnswerForm();
- // 向要提交的表单添加默认答复
- List<FormField> fields = form.getFields();
- for (int i = 0; fields != null && i < fields.size(); i++) {
- if (FormField.Type.hidden != fields.get(i).getType() &&
- fields.get(i).getVariable() != null) {
- // 设置默认值作为答复
- submitForm.setDefaultAnswer(fields.get(i).getVariable());
- }
- }
- // 设置聊天室的新拥有者
- List owners = new ArrayList();
- owners.add(connection.getUser());// 用户JID
- submitForm.setAnswer("muc#roomconfig_roomowners", owners);
- // 设置聊天室是持久聊天室,即将要被保存下来
- submitForm.setAnswer("muc#roomconfig_persistentroom", true);
- // 房间仅对成员开放
- submitForm.setAnswer("muc#roomconfig_membersonly", false);
- // 允许占有者邀请其他人
- submitForm.setAnswer("muc#roomconfig_allowinvites", true);
- if (password != null && password.length() != 0) {
- // 进入是否需要密码
- submitForm.setAnswer("muc#roomconfig_passwordprotectedroom", true);
- // 设置进入密码
- submitForm.setAnswer("muc#roomconfig_roomsecret", password);
- }
- // 能够发现占有者真实 JID 的角色
- // submitForm.setAnswer("muc#roomconfig_whois", "anyone");
- // 登录房间对话
- submitForm.setAnswer("muc#roomconfig_enablelogging", true);
- // 仅允许注册的昵称登录
- submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
- // 允许使用者修改昵称
- submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
- // 允许用户注册房间
- submitForm.setAnswer("x-muc#roomconfig_registration", false);
- // 发送已完成的表单(有默认值)到服务器来配置聊天室
- muc.sendConfigurationForm(submitForm);
- } else {
- }
- } catch (XMPPException | SmackException e) {
- e.printStackTrace();
- return null;
- }
- return muc;
- }
- /**
- * 加入一个群聊聊天室
- *
- * @param jid 聊天室ip 格式为>>群组名称@conference.ip
- * @param nickName 用户在聊天室中的昵称
- * @param password 聊天室密码 没有密码则传""
- * @return
- */
- public MultiUserChat join(String jid, String nickName, String password) {
- try {
- // 使用XMPPConnection创建一个MultiUserChat窗口
- MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
- // 聊天室服务将会决定要接受的历史记录数量
- DiscussionHistory history = new DiscussionHistory();
- history.setMaxChars(0);
- // 用户加入聊天室
- muc.join(nickName, password);
- return muc;
- } catch (XMPPException | SmackException e) {
- e.printStackTrace();
- if ("XMPPError: not-authorized - auth".equals(e.getMessage())) {
- //需要密码加入
- }
- return null;
- }
- }
- /**
- * 获取服务器上的聊天室
- */
- public List<HostedRoom> getHostedRoom() {
- MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
- try {
- //serviceNames->conference.106.14.20.176
- List<String> serviceNames = manager.getServiceNames();
- for (int i = 0; i < serviceNames.size(); i++) {
- return manager.getHostedRooms(serviceNames.get(i));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * @param jid 格式为>>群组名称@conference.ip
- */
- private void initRoomListener(String jid) {
- MultiUserChat multiUserChat = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
- multiUserChat.addMessageListener(new MessageListener() {
- @Override
- public void processMessage(final Message message) {
- //当消息返回为空的时候,表示用户正在聊天窗口编辑信息并未发出消息
- if (!TextUtils.isEmpty(message.getBody())) {
- //收到的消息
- }
- }
- });
- //发送群聊消息
- // MultiUserChat multiUserChat = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(jid);
- // multiUserChat.sendMessage("Hello World");
- }
- // /**
- // * 创建房间
- // *
- // * @param roomName 房间名称
- // */
- // public MultiUserChat createRoom(String roomName, String password) {
- // if (getConnection() == null)
- // return null;
- //
- // MultiUserChat muc = null;
- // try {
- // // 创建一个MultiUserChat
- // muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(roomName+"@conference.192.168.0.195");
- // // 创建聊天室
- // muc.create(roomName);
- // // 获得聊天室的配置表单
- // Form form = muc.getConfigurationForm();
- // // 根据原始表单创建一个要提交的新表单。
- // Form submitForm = form.createAnswerForm();
- // // 向要提交的表单添加默认答复
- // for (FormField formField : form.getFields()) {
- // if (FormField.Type.hidden == formField.getType()
- // && formField.getVariable() != null) {
- // // 设置默认值作为答复
- // submitForm.setDefaultAnswer(formField.getVariable());
- // }
- // }
- // // 设置聊天室的新拥有者
- // List<String> owners = new ArrayList<>();
- // owners.add(getConnection().getUser());// 用户JID
- // submitForm.setAnswer("muc#roomconfig_roomowners", owners);
- // // 设置聊天室是持久聊天室,即将要被保存下来
- // submitForm.setAnswer("muc#roomconfig_persistentroom", true);
- // // 房间仅对成员开放
- // submitForm.setAnswer("muc#roomconfig_membersonly", false);
- // // 允许占有者邀请其他人
- // submitForm.setAnswer("muc#roomconfig_allowinvites", true);
- // if (!password.equals("")) {
- // // 进入是否需要密码
- // submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",
- // true);
- // // 设置进入密码
- // submitForm.setAnswer("muc#roomconfig_roomsecret", password);
- // }
- // // 能够发现占有者真实 JID 的角色
- // // submitForm.setAnswer("muc#roomconfig_whois", "anyone");
- // // 登录房间对话
- // submitForm.setAnswer("muc#roomconfig_enablelogging", true);
- // // 仅允许注册的昵称登录
- // submitForm.setAnswer("x-muc#roomconfig_reservednick", true);
- // // 允许使用者修改昵称
- // submitForm.setAnswer("x-muc#roomconfig_canchangenick", false);
- // // 允许用户注册房间
- // submitForm.setAnswer("x-muc#roomconfig_registration", false);
- // // 发送已完成的表单(有默认值)到服务器来配置聊天室
- // muc.sendConfigurationForm(submitForm);
- // } catch (Exception e) {
- // e.printStackTrace();
- // LoggerUtil.systemOut(e.toString());
- // return null;
- // }
- // return muc;
- // }
- /**
- * 加入会议室
- *
- * @param user 昵称
- * @param roomsName 会议室名
- */
- public MultiUserChat joinMultiUserChat(String user, String roomsName) {
- if (getConnection() == null)
- return null;
- try {
- // 使用XMPPConnection创建一个MultiUserChat窗口
- MultiUserChat muc = MultiUserChatManager.getInstanceFor(connection).getMultiUserChat(connection.getServiceName());
- // 用户加入聊天室
- muc.join(user);
- Log.i("MultiUserChat", "会议室【" + roomsName + "】加入成功........");
- return muc;
- } catch (Exception e) {
- e.printStackTrace();
- Log.i("MultiUserChat", "会议室【" + roomsName + "】加入失败........");
- return null;
- }
- }
- /**
- * 判断是否是好友
- *
- * @param
- * @param user
- * @return
- */
- public boolean isMyFriend(String user) {
- List<RosterEntry> allEntries = XmppConnection.getInstance().getAllEntries();
- for (int i = 0; i < allEntries.size(); i++) {
- LoggerUtil.systemOut("allEntries.get(i).getUser() == " + allEntries.get(i).getUser());
- LoggerUtil.systemOut("user == " + user);
- if (allEntries.get(i).getUser().equals(user)) {
- LoggerUtil.systemOut(allEntries.get(i).getType().toString() + "type");
- if (allEntries.get(i).getType().toString().equals("both")) {
- return true;
- } else {
- return false;
- }
- }
- }
- return false;
- }
- /**
- * 查询会议室成员名字
- *
- * @param muc
- */
- public List<String> findMulitUser(MultiUserChat muc) {
- if (getConnection() == null)
- return null;
- List<String> listUser = new ArrayList<>();
- List<String> occupants = muc.getOccupants();
- // 遍历出聊天室人员名称
- for (String entityFullJid : occupants) {
- // 聊天室成员名字
- String name = entityFullJid;
- listUser.add(name);
- }
- return listUser;
- }
- /**
- * 判断OpenFire用户的状态 strUrl :
- * url格式 - http://my.openfire.com:9090/plugins/presence
- * /status?jid=user1@SERVER_NAME&type=xml
- * 返回值 : 0 - 用户不存在; 1 - 用户在线; 2 - 用户离线
- * 说明 :必须要求 OpenFire加载 presence 插件,同时设置任何人都可以访问
- */
- public int IsUserOnLine(String user) {
- String url = "http://" + SERVER_HOST + ":9090/plugins/presence/status?" +
- "jid=" + user;
- int shOnLineState = 0; // 不存在
- try {
- URL oUrl = new URL(url);
- URLConnection oConn = oUrl.openConnection();
- if (oConn != null) {
- BufferedReader oIn = new BufferedReader(new InputStreamReader(
- oConn.getInputStream()));
- String strFlag = oIn.readLine();
- oIn.close();
- System.out.println("strFlag" + strFlag);
- if (strFlag.contains("type=\"unavailable\"")) {
- shOnLineState = 2;
- }
- if (strFlag.contains("type=\"error\"")) {
- shOnLineState = 0;
- } else if (strFlag.contains("priority") || strFlag.contains("id=\"")) {
- shOnLineState = 1;
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return shOnLineState;
- }
- /**
- * 创建聊天窗口
- *
- * @param JID JID
- * @return Chat
- */
- public Chat getFriendChat(String JID, ChatMessageListener listener) {
- try {
- return ChatManager.getInstanceFor(XmppConnection.getInstance().getConnection())
- .createChat(JID, listener);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 发送单人聊天消息
- *
- * @param chat chat
- * @param message 消息文本
- */
- public void sendSingleMessage(Chat chat, String message) {
- try {
- chat.sendMessage(message);
- } catch (SmackException.NotConnectedException e) {
- e.printStackTrace();
- }
- }
- /**
- * 发消息
- *
- * @param chat chat
- * @param muc muc
- * @param message message
- */
- public void sendMessage(Chat chat, MultiUserChat muc, String message) {
- if (chat != null) {
- sendSingleMessage(chat, message);
- } else if (muc != null) {
- sendGroupMessage(muc, message);
- }
- }
- /**
- * 获取离线消息
- *
- * @return
- */
- int i = 0;
- public void getHisMessage(Context context) {
- LoggerUtil.systemOut("访问次数 " + (i++));
- setPresence(5);
- if (getConnection() == null)
- return;
- try {
- OfflineMessageManager offlineManager = new OfflineMessageManager(getConnection());
- List<Message> messageList = offlineManager.getMessages();
- int count = offlineManager.getMessageCount();
- LoggerUtil.systemOut("离线消息个数" + count);
- if (count <= 0) {
- setPresence(0);
- return;
- }
- for (Message message : messageList) {
- String[] send = message.getFrom().split("@");// 发送方
- String[] receiver = message.getTo().split("@");// 接收方
- saveofflineMessage(context, receiver[0], send[0], send[0], message.getBody(), "chat");
- saveofflineChatData(context, receiver[0], send[0], send[0], message.getBody());
- }
- offlineManager.deleteMessages();
- } catch (Exception e) {
- e.printStackTrace();
- }
- setPresence(0);
- }
- public boolean saveofflineMessage(Context context, String main, final String users, final String to, final String content, String type) {
- Cursor cursor = MessageDao.getInstance(context).queryIshasResult(context, 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(context).update(context, id, content, 1);
- return true;
- } else {
- return false;
- }
- } else {
- int id = cursor.getInt(cursor.getColumnIndex("id"));
- MessageDao.getInstance(context).update(context, id, content, 1);
- 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(context).inserts(context, xm);
- return true;
- }
- }
- public void saveofflineChatData(Context context, String main, final String users, final String to, final String content) {
- XmppChat xc = new XmppChat(main, users, "", "", 2, content, to, 1, new Date().getTime());
- FriendChatDao.getInstance(context).insert(context, xc);
- }
- /**
- * 注册
- *
- * @param account 注册帐号
- * @param password 注册密码
- * @return 1、注册成功 0、注册失败
- */
- public boolean register(String account, String password, String nickName) {
- if (getConnection() == null)
- return false;
- try {
- // new
- Map<String, String> attributes = new HashMap<>();
- attributes.put("name", nickName);
- AccountManager.getInstance(connection).createAccount(account, password, attributes);
- } catch (XMPPException | SmackException e) {
- e.printStackTrace();
- return false;
- }
- return true;
- }
- /**
- * 设置昵称
- *
- * @param
- * @param rosterEntry
- * @return
- */
- public boolean setNickName(RosterEntry rosterEntry, String nickName) {
- try {
- rosterEntry.setName(nickName);
- return true;
- } catch (SmackException.NotConnectedException e) {
- e.printStackTrace();
- return false;
- } catch (SmackException.NoResponseException e) {
- e.printStackTrace();
- return false;
- } catch (XMPPException.XMPPErrorException e) {
- e.printStackTrace();
- return false;
- }
- }
- private OutgoingFileTransfer fileTransfer;
- // 发送文件
- public void sendFile(String user, File file) throws Exception {
- FileTransferManager instanceFor = FileTransferManager.getInstanceFor(connection);
- fileTransfer = instanceFor.createOutgoingFileTransfer(user);
- fileTransfer.sendFile(file, "send file");
- System.out.println("发送成功" + user + file.exists() + "文件路径" + file.getPath());
- }
- /*
- * 语音接收文件监听接收文件
- *
- * @author Administrator
- *
- */
- private FileTransferListener mfiletransfransferlistener;//接受语音文件监听
- public void receivedFile() {
- // Create the file transfer manager
- FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
- mfiletransfransferlistener = new FileTransferListener() {
- public void fileTransferRequest(FileTransferRequest request) {
- // Check to see if the request should be accepted
- LoggerUtil.systemOut("有文件接收了" + request.toString());
- // Accept it
- IncomingFileTransfer transfer = request.accept();
- try {
- File filePath = new File(Environment.getExternalStorageDirectory(), "fcyt");
- if (!filePath.exists()) {
- filePath.mkdirs();
- }
- // File file = new File( Environment
- // .getExternalStorageDirectory()+"/fcyt/"
- // +"/"+ request.getFileName());
- String streamID = request.getStreamID();
- LoggerUtil.systemOut("streamID", streamID);
- File file = new File(filePath, request.getFileName());
- System.out.println(request.getFileName() + "接收路径" + file.getPath() + "接收语音文件名称" + file.exists());
- transfer.recieveFile(file);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- };
- manager.addFileTransferListener(mfiletransfransferlistener);
- }
- /**
- * 查找用户
- *
- * @param
- * @param userName
- * @return
- */
- public List<XmppUser> searchUsers(String userName) {
- List<XmppUser> list = new ArrayList<XmppUser>();
- UserSearchManager userSearchManager = new UserSearchManager(connection);
- try {
- Form searchForm = userSearchManager.getSearchForm("search."
- + connection.getServiceName());
- Form answerForm = searchForm.createAnswerForm();
- answerForm.setAnswer("Username", true);
- answerForm.setAnswer("Name", true);
- answerForm.setAnswer("search", userName);
- ReportedData data = userSearchManager.getSearchResults(answerForm, "search." + connection.getServiceName());
- List<ReportedData.Row> rows = data.getRows();
- for (ReportedData.Row row : rows) {
- XmppUser user = new XmppUser(null, null);
- user.setUserName(row.getValues("Username").toString().replace("]", "").replace("[", ""));
- user.setName(row.getValues("Name").toString().replace("]", "").replace("[", ""));
- list.add(user);
- }
- } catch (Exception e) {
- }
- return list;
- }
- public static void configure(ProviderManager pm) {
- try {
- Class.forName("org.jivesoftware.smack.ReconnectionManager");
- } catch (Exception e) {
- e.printStackTrace();
- }
- // Private Data Storage
- pm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());
- // Time
- try {
- pm.addIQProvider("query", "jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
- } catch (ClassNotFoundException e) {
- Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time");
- }
- // // Roster Exchange
- // pm.addExtensionProvider("x", "jabber:x:roster", new RosterLoadedListener() {
- // });
- //
- // // Message Events
- // pm.addExtensionProvider("x", "jabber:x:event", new MessageEventProvider());
- // Chat State
- pm.addExtensionProvider("active", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
- pm.addExtensionProvider("composing", "http://jabber.org/protocol/chatstates",
- new ChatStateExtension.Provider());
- pm.addExtensionProvider("paused", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
- pm.addExtensionProvider("inactive", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
- pm.addExtensionProvider("gone", "http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
- // XHTML
- pm.addExtensionProvider("html", "http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());
- // Group Chat Invitations
- pm.addExtensionProvider("x", "jabber:x:conference", new GroupChatInvitation.Provider());
- // Service Discovery # Items
- pm.addIQProvider("query", "http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
- // Service Discovery # Info
- pm.addIQProvider("query", "http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
- // Data Forms
- pm.addExtensionProvider("x", "jabber:x:data", new DataFormProvider());
- // MUC User
- pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());
- // MUC Admin
- pm.addIQProvider("query", "http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
- // MUC Owner
- pm.addIQProvider("query", "http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
- // Delayed Delivery
- pm.addExtensionProvider("x", "jabber:x:delay", new DelayInformationProvider());
- // Version
- try {
- pm.addIQProvider("query", "jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
- } catch (ClassNotFoundException e) {
- // Not sure what's happening here.
- }
- // VCard
- pm.addIQProvider("vCard", "vcard-temp", new VCardProvider());
- // Offline Message Requests
- pm.addIQProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
- // Offline Message Indicator
- pm.addExtensionProvider("offline", "http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
- // Last Activity
- pm.addIQProvider("query", "jabber:iq:last", new LastActivity.Provider());
- // User Search
- pm.addIQProvider("query", "jabber:iq:search", new UserSearch.Provider());
- // SharedGroupsInfo
- pm.addIQProvider("sharedgroup", "http://www.jivesoftware.org/protocol/sharedgroup",
- new SharedGroupsInfo.Provider());
- // JEP-33: Extended Stanza Addressing
- pm.addExtensionProvider("addresses", "http://jabber.org/protocol/address", new MultipleAddressesProvider());
- // FileTransfer
- pm.addIQProvider("si", "http://jabber.org/protocol/si", new StreamInitiationProvider());
- pm.addIQProvider("query", "http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
- pm.addIQProvider("open", "http://jabber.org/protocol/ibb", new OpenIQProvider());
- pm.addIQProvider("close", "http://jabber.org/protocol/ibb", new CloseIQProvider());
- // pm.addExtensionProvider("data", "http://jabber.org/protocol/ibb", new DataPacketProvider());
- // Privacy
- pm.addIQProvider("query", "jabber:iq:privacy", new PrivacyProvider());
- pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
- pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands",
- new AdHocCommandDataProvider.MalformedActionError());
- pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands",
- new AdHocCommandDataProvider.BadLocaleError());
- pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands",
- new AdHocCommandDataProvider.BadPayloadError());
- pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands",
- new AdHocCommandDataProvider.BadSessionIDError());
- pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands",
- new AdHocCommandDataProvider.SessionExpiredError());
- }
- }
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实现的更多相关文章
- openfire+asmack搭建的安卓即时通讯(一) 15.4.7
最进开始做一些android的项目,除了一个新闻客户端的搭建,还需要一个实现一个即时通讯的功能,参考了很多大神成型的实例,了解到operfire+asmack是搭建简易即时通讯比较方便,所以就写了这篇 ...
- xmpp openfire smack 介绍和openfire安装及使用
前言 Java领域的即时通信的解决方案可以考虑openfire+spark+smack.当然也有其他的选择. Openfire是基于Jabber协议(XMPP)实现的即时通信服务器端版本,目前建议使用 ...
- 使用ruby搭建简易的http服务和sass环境
使用ruby搭建简易的http服务和sass环境 由于在通常的前端开发情况下,我们会有可能需要一个http服务,当然你可以选择自己写一个node的http服务,也比较简单,比如下面的node代码: v ...
- Django搭建简易博客
Django简易博客,主要实现了以下功能 连接数据库 创建超级用户与后台管理 利用django-admin-bootstrap美化界面 template,view与动态URL 多说评论功能 Markd ...
- 基于xmpp openfire smack开发之Android客户端开发[3]
在上两篇文章中,我们依次介绍openfire部署以及smack常用API的使用,这一节中我们着力介绍如何基于asmack开发一个Android的客户端,本篇的重点在实践,讲解和原理环节,大家可以参考前 ...
- EditPlus+MinGW搭建简易的C/C++开发环境
EditPlus+MinGW搭建简易的C/C++开发环境 有时候想用C编点小程序,但是每次都要启动那难用又难看的VC实在是不情愿,而且老是会生成很多没用的中间文件,很讨厌,后来看到网上有很多人用Edi ...
- Python中使用Flask、MongoDB搭建简易图片服务器
主要介绍了Python中使用Flask.MongoDB搭建简易图片服务器,本文是一个详细完整的教程,需要的朋友可以参考下 1.前期准备 通过 pip 或 easy_install 安装了 pymong ...
- express搭建简易web的服务器
express搭建简易web的服务器 说到express我们就会想到nodejs,应为它是一款基于nodejs平台的web应用开发框架.既然它是基于nodejs平台的框架那么就得先安装nodejs. ...
- openfire+smack 实现即时通讯基本框架
smack jar下载地址 http://www.igniterealtime.org/downloads/download-landing.jsp?file=smack/smack_3_2_2.zi ...
随机推荐
- CentOS7 SVN基本配置
开机自启指令如下 systemctl enable svnserve.service 对应可执行脚本文件路径 vim /etc/sysconfig/svnserve 查看状态: ps -ef|grep ...
- RT-Thread中的串口DMA分析
这里分析一下RT-Thread中串口DMA方式的实现,以供做新处理器串口支持时的参考. 背景 在如今的芯片性能和外设强大功能的情况下,串口不实现DMA/中断方式操作,我认为在实际项目中基本是不可接受的 ...
- python-迭代器与生成器3
python-迭代器与生成器3 迭代器可以直接作用于for循环的数据类型有以下几种: 一类是集合数据类型,如list.tuple.dict.set.str等: 一类是generator,包括生成器和带 ...
- 浙大数据结构课后习题 练习二 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 ...
- Highcharts动态获取值
<script type="text/javascript"> $(document).ready(function (){ var o ...
- 高性能mysql 第10章 复制
复制功能不仅能够构建高可用的应用,同时也是高可用性,可扩展性,灾难恢复,备份以及数据仓库等工作的基础. mysql支持两种复制方式:基于语句的复制和基于行的复制.基于语句的复制(也成为逻辑复制)是早期 ...
- 我说CMMI之一:CMMI是什么--转载
我说CMMI之一:CMMI是什么 有些朋友没有接触过CMMI,正在学习CMMI,CMMI本身的描述比较抽象,所以,读起来有些费劲.有些朋友实施过CMMI,但是可能存在对CMMI的一些误解,因此我想说说 ...
- k8s管理pod资源对象(下)
一.标签与标签选择器 1.标签是k8s极具特色的功能之一,它能够附加于k8s的任何资源对象之上.简单来说,标签就是键值类型的数据,它们可于资源创建时直接指定,也可随时按需添加于活动对象中,而后即可由标 ...
- ToolStrip 选中某一项打勾
(sender as ToolStripMenuItem).Checked = !(sender as ToolStripMenuItem).Checked;
- 【C#-算法】根据生日自动计算年龄_DataTime 的 DateDiff 方法
dateTimePicker1.Value出生日期控件的值 long BirthDay = DateAndTime.DateDiff(DateInterval.Year, dateTimePicker ...