xmpp的XmppConnection类

xiaoxiao2021-02-28  54

public class XmppConnection { private static XMPPConnection connection = null; private static XmppConnection xmppConnection; public Roster roster; private static Chat newchat; private static MultiUserChat mulChat; private XmppConnecionListener connectionListener; private XmppMessageInterceptor xmppMessageInterceptor; private XmppMessageListener messageListener; public static List<Room> myRooms = new ArrayList<Room>(); public static List<Room> leaveRooms = new ArrayList<Room>(); private HashMap<String, MultiUserChat> mucMap = new HashMap<String, MultiUserChat>(); protected String TAG = getClass().getSimpleName().toString(); private MyPerference mp; ConnectionConfiguration config; /** 打开连接次数统计 */ private int openConnCount = 0; // static { // try { // Class.forName("org.jivesoftware.smack.ReconnectionManager"); // } catch (Exception e) { // e.printStackTrace(); // } // } /** * 单例模式 * * @return */ public static XmppConnection getInstance() { if (xmppConnection == null) { xmppConnection = new XmppConnection(); } return xmppConnection; } public void setNull() { connection = null; } // 是否掉线 public static boolean unOnlice() { return connection.isConnected(); } /** * 创建连接 */ public XMPPConnection getConnection() { openConnCount = 0; if (connection == null || !connection.isConnected()) { openConnection(); } Log.e("测试yu", connection == null ? "connection is null" : "connection is not null"); return connection; } /** * 打开连接 */ public boolean openConnection() { try { if (null == connection || !connection.isAuthenticated()) {// isAuthenticated()返回真实,如果当前身份验证成功调用登录方法。 XMPPConnection.DEBUG_ENABLED = true;// 开启DEBUG模式 // 配置连接 mp=new MyPerference(MyApplication.getContext()); config = new ConnectionConfiguration(Constants.SERVER_HOST_POINT, Constants.SERVER_PORT, Constants.SERVER_NAME); // if (Build.VERSION.SDK_INT >= 14) { // config.setKeystoreType("AndroidCAStore"); //$NON-NLS-1$ // config.setTruststorePassword(null); // config.setKeystorePath(null); // } else { // config.setKeystoreType("BKS"); //$NON-NLS-1$ // String path = System.getProperty("javax.net.ssl.trustStore"); // //$NON-NLS-1$ // if (path == null) // path = System.getProperty("java.home") + File.separator // //$NON-NLS-1$ // + "etc" + File.separator + "security" //$NON-NLS-1$ // //$NON-NLS-2$ // + File.separator + "cacerts.bks"; //$NON-NLS-1$ // config.setKeystorePath(path); // } // config.setSASLAuthenticationEnabled(false); config.setReconnectionAllowed(true);// // 设置如果允许使用重联机制。默认重联是可以的。 // Sets the TLS security mode used when making the connection. // By default, the mode is // ConnectionConfiguration.SecurityMode.enabled. // config.setReconnectionAllowed(true); config.setSecurityMode(SecurityMode.disabled); new Thread(new Runnable() { @Override public void run() { config.setSASLAuthenticationEnabled(false);// 设置客户端是否将使用SASL认证登录到服务器时。如果SASL认证失败,则客户端将尝试使用非SASL认证。默认情况下,启用SASL。 } }).start(); config.setSendPresence(false); // 状态设为离线,目的为了取离线消息 connection = new XMPPConnection(config); // 自动回复回执方法, ProviderManager pm = ProviderManager.getInstance(); pm.addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider()); pm.addExtensionProvider(DeliveryReceiptRequest.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceiptRequest.Provider()); DeliveryReceiptManager.getInstanceFor(connection).enableAutoReceipts(); connection.connect();// 连接到服务器 // 配置各种Provider,如果不配置,则会无法解析数据 configureConnection(ProviderManager.getInstance()); // 添加連接監聽 connectionListener = new XmppConnecionListener(); connection.addConnectionListener(connectionListener); xmppMessageInterceptor = new XmppMessageInterceptor(); connection.addPacketInterceptor(xmppMessageInterceptor, new PacketTypeFilter(Message.class)); messageListener = new XmppMessageListener(); connection.addPacketListener(messageListener, new PacketTypeFilter(Message.class)); // //非自动回复回执方法 // connection.addPacketListener(new PacketListener() { // public void processPacket(Packet packet) { // // 监听消息,在检查到对方要求回执时,客户端手动发送回执给对方 // if (packet instanceof Message) { // Message message = (Message) packet; // PacketExtension receipt = message.getExtension(DeliveryReceiptRequest.ELEMENT, // DeliveryReceipt.NAMESPACE); // if (receipt != null) { // Message receiptMessage = new Message(); // receiptMessage.setTo(message.getFrom()); // receiptMessage.setFrom(message.getTo()); // receiptMessage.setType(Message.Type.chat); // receiptMessage.addExtension(new DeliveryReceipt(message.getPacketID())); // connection.sendPacket(receiptMessage); // } // } // } // }, new PacketFilter() { // public boolean accept(Packet packet) { // return true; // } // }); // connection.addPacketListener(new XmppPresenceListener(), // new PacketTypeFilter(Presence.class)); // connection.addPacketListener(arg0, arg1); ProviderManager.getInstance().addIQProvider("muc", "MZH", new MUCPacketExtensionProvider()); DeliveryReceiptManager.getInstanceFor(connection).enableAutoReceipts(); // new Thread() { // public void run() { // while (true) { // try { // sleep(1000 * 20); // } catch (InterruptedException e) { // e.printStackTrace(); // } // if (connection != null) { // PingManager.getInstanceFor(connection) // .pingMyServer(); // } // } // }; // }.start(); /* 调用系统ping */ PingManager.getInstanceFor(connection).pingMyServer(1000 * 20); // PingManager.getInstanceFor(connection).setPingIntervall(20); PingManager.getInstanceFor(connection).registerPingFailedListener(new PingFailedListener() { @Override public void pingFailed() { reconnect(); } }); return true; } } catch (XMPPException xe) { Log.e("测试yu", "open connection is XMPPException"); xe.printStackTrace(); connection = null; if (openConnCount < 2) { // if(mp.getBoolean("isOutNewWork", false)){ // mp.saveBoolean("isOutNewWork", false); // }else { // mp.saveBoolean("isOutNewWork", true); // } openConnCount++; openConnection(); } } catch (Exception e) { Log.e("测试yu", "open connection is Exception and type is " + e.getStackTrace()[1].getClassName()); e.printStackTrace(); if (openConnCount < 2) { openConnCount++; openConnection(); } } return false; } /** * 关闭连接 */ public void closeConnection(boolean reconnect) { if (connection != null) { // 断开连接的时候移除监听---解决网络不好时出现发送两次的情况(未验证是否已解决) if (messageListener != null) { connection.removePacketListener(messageListener); connection.removePacketInterceptor(xmppMessageInterceptor); } if (connectionListener != null) { connection.removeConnectionListener(connectionListener); } ProviderManager.getInstance().removeIQProvider("muc", "MZH"); try { connection.disconnect(); } catch (Exception e) { if (Constants.IS_DEBUG) Log.e("asmack dis", e.getMessage()); e.printStackTrace(); } finally { connection = null; xmppConnection = null; } } if (Constants.IS_DEBUG) Log.e("XmppConnection", "close connection"); if (reconnect) { reconnect(); } } public void reconnect() { new Thread() { @Override public void run() { try { sleep(5 * 1000); ChatActivity.isLeaving = true; ChatRoomActivity.isLeaving = true; closeConnection(false); if (login(Constants.USER_NAME, Constants.PWD)) { Log.e("测试yu", "登录成功"); } } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { } super.run(); } }.start(); } /** * 999999 访问后台 获取 聊天室列表 挨个聊天室加入 * * @param userid */ public void joinChatRoom(String userid) { APIClient.getChatRoom(userid, new AsyncHttpResponseHandler() { @Override protected void onPreExecute() { super.onPreExecute(); } @Override public void onFinish() { super.onFinish(); } @Override public void onSuccess(int statusCode, String content) { super.onSuccess(statusCode, content); try { if (!"400".equals(new JSONObject(content).getString("status"))) { Gson gson = new Gson(); BaseResponse<ChatRoomEntity> response = gson.fromJson(content, new TypeToken<BaseResponse<ChatRoomEntity>>() { }.getType()); ArrayList<ChatRoomEntity> data = (ArrayList<ChatRoomEntity>) response.getData(); // ChatRoomDbHelper.getInstance( // MyApplication.getInstance()).deleteAllChatRoom( // Constants.USER_NAME); if (data != null && data.size() > 0) { for (ChatRoomEntity chatRoomEntity : data) { if ("2".equals(chatRoomEntity.getJoinState())) { ChatItem chatItem = null; chatItem = MsgDbHelper.getInstance(MyApplication.getInstance()) .getChatLastMsg(chatRoomEntity.getRoomId(), ChatItem.GROUP_CHAT); Date date = null; if (chatItem != null) { date = DateUtil.strToDateCN_yyyy_MM_dd_HH_mm_ss_SSS(chatItem.sendDate); } else { date = DateUtil.strToDateCN_yyyy_MM_dd_HH_mm_ss_SSS( ChatRoomDbHelper.getInstance(MyApplication.getInstance()) .getChatRoomTime(chatRoomEntity.getRoomId())); } ChatRoomDbHelper.getInstance(MyApplication.getInstance()) .checkAndSaveRoom(chatRoomEntity); if (Constants.USER_NAME != null && !"".equals(Constants.USER_NAME)) { XmppConnection.getInstance().joinMultiUserChat(Constants.USER_NAME, chatRoomEntity.getRoomName(), false, date); } else { return; } } } MyApplication.getInstance().sendBroadcast(new Intent("newChatRoom")); } } } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(Throwable error, String content) { Log.i("", content); super.onFailure(error, content); } }); } public void loadFriendAndJoinRoom() { new Thread() { public void run() { try { sleep(1 * 1000); ChatActivity.isLeaving = false; ChatRoomActivity.isLeaving = false; } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); } /** * 登录 * * @param account * 登录帐号 * @param password * 登录密码 * onKeydown * @return */ public boolean login(String account, String password) throws Exception { try { Log.e("tjj", "开始登录"); if (getConnection() == null) { // return false; throw new Exception("Exception"); } if (!getConnection().isAuthenticated() && getConnection().isConnected()) { getConnection().login(account, password); // 更改在綫狀態 Presence presence = new Presence(Presence.Type.available); // Constants.USER_STATUS = presence.getStatus(); // OfflineMessageManager offlineManager = new // OfflineMessageManager(getConnection()); // Iterator<org.jivesoftware.smack.packet.Message> it = // offlineManager.getMessages(); // while(it.hasNext()){ // org.jivesoftware.smack.packet.Message message = it.next(); // // Log.e("tjj", "收到离线消息, Received from 【" + message.getFrom() + // "】 message: " + message.getBody()); // // NewMsgDbHelper.getInstance(MyApplication.getInstance()) // // .saveNewMsg(getUsername(message.getFrom())); // Log.e(TAG,getUsername(message.getFrom())); // // // MsgDbHelper.getInstance(MyApplication.getInstance()).saveChatMsgId(getUsername(message.getFrom()), // DateUtil.dateToStr_yyyy_MM_dd_HH_mm_ss_SSS(new Date())); // messageListener.processPacket(message); // } // //删除离线消息 // offlineManager.deleteMessages(); // 将状态设置成在线 presence.setMode(Presence.Mode.available); getConnection().sendPacket(presence); // roster = XmppConnection.getInstance().getConnection() // .getRoster(); // friendListner = new FriendListner(); // roster.addRosterListener(friendListner); // 监听邀请加入聊天室请求 MultiUserChat.addInvitationListener(getConnection(), new InvitationListener() { @Override public void invitationReceived(Connection conn, String room, String inviter, String reason, String password, Message message) { } }); loadFriendAndJoinRoom(); String userid = new MyPerference(MyApplication.getInstance()).getString("userid", ""); // Log.e("tjj", "========userid========="+userid); if (!"".equals(userid)) { joinChatRoom(userid); } return true; } } catch (XMPPException e) { return false; } catch (IllegalStateException e) { e.fillInStackTrace(); return true; } return false; } /** * 收到新邀请后 更改后台数据 * * @param roomName */ protected void updateJoinState(final String roomName) { APIClient.updateJoinState(new MyPerference(MyApplication.getInstance()).getString("userid", ""), roomName, new AsyncHttpResponseHandler() { @Override protected void onPreExecute() { super.onPreExecute(); } @Override public void onFinish() { super.onFinish(); } @Override public void onSuccess(int statusCode, String content) { JSONObject jsonObject; try { jsonObject = new JSONObject(content); if ("200".equals(jsonObject.getString("status"))) { } else { LogUtil.i("修改聊天室状态", "修改加入聊天室状态失败"); } } catch (JSONException e) { e.printStackTrace(); } super.onSuccess(statusCode, content); } @Override public void onFailure(Throwable error, String content) { LogUtil.i("修改聊天室状态", "网络异常 "); super.onFailure(error, content); } }); } /** * 注册 * * @param account * 注册帐号 * @param password * 注册密码 * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败 */ public IQ regist(String account, String password) { if (getConnection() == null) return null; Registration reg = new Registration(); reg.setType(IQ.Type.SET); reg.setTo(getConnection().getServiceName()); reg.setUsername(account); reg.setPassword(password); // reg.addAttribute("android", "geolo_createUser_android"); PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = getConnection().createPacketCollector(filter); // 给注册的Packet设置Listener,因为只有等到正真注册成功后,我们才可以交流 // collector.addPacketListener(packetListener, filter); // 向服务器端,发送注册Packet包,注意其中Registration是Packet的子类 getConnection().sendPacket(reg); IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); // Stop queuing results collector.cancel(); return result; } /** * 修改密码 * * @param pwd * @return */ public boolean changPwd(String pwd) { try { getConnection().getAccountManager().changePassword(pwd); return true; } catch (XMPPException e) { e.printStackTrace(); return false; } } public void setRecevier(String chatName, int chatType) { if (getConnection() == null) return; if (chatType == ChatItem.CHAT) { // 创建回话 ChatManager cm = XmppConnection.getInstance().getConnection().getChatManager(); // 发送消息给pc服务器的好友(获取自己的服务器,和好友) newchat = cm.createChat(getFullUsername(chatName), null); } else if (chatType == ChatItem.GROUP_CHAT) { mulChat = new MultiUserChat(getConnection(), getFullRoomname(chatName)); } } // 发送文本消息 @SuppressLint("NewApi") public void sendMsg(String chatName, final String msg, int chatType) throws Exception { if (getConnection() == null) { throw new Exception("XmppException"); } // if (!NetWorkUtil.ping()) { // throw new Exception("NoNetException"); // } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); if (msg.isEmpty()) { ToastUtil.showShort(MyApplication.getInstance(), "随便写点什么呗"); } else { if (chatType == ChatItem.CHAT) { ChatManager cm = XmppConnection.getInstance().getConnection().getChatManager(); // 发送消息给pc服务器的好友(获取自己的服务器,和好友) final Chat newchat = cm.createChat(getFullUsername(chatName), null); message.setPacketID(UUID.randomUUID().toString()); message.setBody(msg); DeliveryReceiptRequest deliveryReceiptRequest = new DeliveryReceiptRequest(); message.addExtension(deliveryReceiptRequest); // DeliveryReceiptManager.addDeliveryReceiptRequest(message);//tjj newchat.sendMessage(message); } else if (chatType == ChatItem.GROUP_CHAT) { Message newMsg = new Message(); newMsg.setPacketID(UUID.randomUUID().toString()); newMsg.setBody(msg); newMsg.setType(Message.Type.groupchat); newMsg.setTo(chatName + "@conference." + getConnection().getServiceName()); // DeliveryReceiptManager.addDeliveryReceiptRequest(newMsg);//tjj if (mucMap.get(chatName) == null) { if (ChatRoomDbHelper.getInstance(MyApplication.getInstance()).checkChatRoom(chatName)) { ChatItem chatItem = null; chatItem = MsgDbHelper.getInstance(MyApplication.getInstance()).getChatLastMsg(chatName, ChatItem.GROUP_CHAT); Date date = null; if (chatItem != null) { date = DateUtil.strToDateCN_yyyy_MM_dd_HH_mm_ss_SSS(chatItem.sendDate); } else { date = DateUtil.strToDateCN_yyyy_MM_dd_HH_mm_ss_SSS(ChatRoomDbHelper .getInstance(MyApplication.getInstance()).getChatRoomTime(chatName)); } joinMultiUserChat(Constants.USER_NAME, chatName, false, date); mucMap.get(chatName).sendMessage(newMsg); // mucMap.get(chatName).sendMessage(msg); } else { handler.sendEmptyMessage(1); } } else { mucMap.get(chatName).sendMessage(newMsg);//389107310970882 // mucMap.get(chatName).sendMessage(msg); } } } } // 发送文本消息 @SuppressLint("NewApi") public void sendMsg(String msg, int chatType) throws Exception { // if (!NetWorkUtil.ping()) { // throw new Exception("NoNetException"); // } if (getConnection() == null) { throw new Exception("XmppException"); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); if (msg.isEmpty()) { ToastUtil.showShort(MyApplication.getInstance(), "随便写点什么呗"); } else { message.setBody(msg); message.setPacketID(UUID.randomUUID().toString()); DeliveryReceiptManager.addDeliveryReceiptRequest(message);//tjj if (chatType == ChatItem.CHAT) { DeliveryReceiptRequest deliveryReceiptRequest = new DeliveryReceiptRequest(); message.addExtension(deliveryReceiptRequest); newchat.sendMessage(message); } else if (chatType == ChatItem.GROUP_CHAT) { mulChat.sendMessage(msg); } } } // 发送消息,附带参数 public void sendMsgWithParms(String msg, String[] parms, Object[] datas, int chatType, String roomId) throws Exception { if (getConnection() == null) { throw new Exception("XmppException"); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); for (int i = 0; i < datas.length; i++) { message.setProperty(parms[i], datas[i]); // Log.e("tjj", "==========parms============="+parms[i]+" "+datas[i]); } message.setPacketID(UUID.randomUUID().toString()); message.setBody(msg); if (chatType == ChatItem.CHAT) { DeliveryReceiptManager.addDeliveryReceiptRequest(message); newchat.sendMessage(message); } else if (chatType == ChatItem.GROUP_CHAT) { // DeliveryReceiptManager.addDeliveryReceiptRequest(message); // mucMap.get(roomId).sendMessage(msg + ":::" + datas[0]);//389107310970882 389107310970882 if (mucMap.get(roomId) == null) { if (ChatRoomDbHelper.getInstance(MyApplication.getInstance()).checkChatRoom(roomId)) { ChatItem chatItem = null; chatItem = MsgDbHelper.getInstance(MyApplication.getInstance()).getChatLastMsg(roomId, ChatItem.GROUP_CHAT); Date date = null; if (chatItem != null) { date = DateUtil.strToDateCN_yyyy_MM_dd_HH_mm_ss_SSS(chatItem.sendDate); } else { date = DateUtil.strToDateCN_yyyy_MM_dd_HH_mm_ss_SSS(ChatRoomDbHelper .getInstance(MyApplication.getInstance()).getChatRoomTime(roomId)); } joinMultiUserChat(Constants.USER_NAME, roomId, false, date); mucMap.get(roomId).sendMessage(msg + ":::" + datas[0]); // mucMap.get(chatName).sendMessage(msg); } else { handler.sendEmptyMessage(1); } } else { mucMap.get(roomId).sendMessage(msg + ":::" + datas[0]); // mucMap.get(chatName).sendMessage(msg); } } } // 发送消息,附带参数,转发 public void sendMsgWithParms(String chatName, String msg, String[] parms, Object[] datas, int chatType, String roomId) throws Exception { if (getConnection() == null) { throw new Exception("XmppException"); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); for (int i = 0; i < datas.length; i++) { message.setProperty(parms[i], datas[i]); } ChatManager cm = XmppConnection.getInstance().getConnection().getChatManager(); // 发送消息给pc服务器的好友(获取自己的服务器,和好友) final Chat newchat = cm.createChat(getFullUsername(chatName), null); message.setPacketID(UUID.randomUUID().toString()); message.setBody(msg); if (chatType == ChatItem.CHAT) { DeliveryReceiptManager.addDeliveryReceiptRequest(message); newchat.sendMessage(message); } else if (chatType == ChatItem.GROUP_CHAT) { DeliveryReceiptManager.addDeliveryReceiptRequest(message);//tjj mucMap.get(roomId).sendMessage(msg + ":::" + datas[0]); } } // 发送邀请消息invitatie public void sendInvitateMsgWithParms(String msg, String[] parms, Object[] datas, int chatType, String roomId) throws Exception { if (getConnection() == null) { throw new Exception("XmppException"); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); for (int i = 0; i < datas.length; i++) { message.setProperty(parms[i], datas[i]); } message.setPacketID(UUID.randomUUID().toString()); message.setBody(msg); /* * message.setType(Type.groupchat); * message.setTo(getFullRoomname(roomId)); * mucMap.get(roomId).sendMessage(message); */ message.setType(Type.chat); message.setTo(getFullUsername((String) datas[0])); //tjj DeliveryReceiptManager.addDeliveryReceiptRequest(message); newchat.sendMessage(message); } // 发送群组邀请消息invitatie public void sendInvitateGroupMsgWithParms(String msg, String[] parms, Object[] datas, int chatType, String roomId) throws Exception { if (getConnection() == null) { throw new Exception("XmppException"); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); for (int i = 0; i < datas.length; i++) { message.setProperty(parms[i], datas[i]); } message.setPacketID(UUID.randomUUID().toString()); message.setBody(msg); message.setType(Type.groupchat); message.setTo(getFullRoomname(roomId)); //tjj DeliveryReceiptManager.addDeliveryReceiptRequest(message); mucMap.get(roomId).sendMessage(message); } // 发送@消息 public void sendATMsg(String msg, String[] parms, Object[] datas, int chatType, String roomId) throws Exception { if (getConnection() == null) { throw new Exception("XmppException"); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); for (int i = 0; i < datas.length; i++) { message.setProperty(parms[i], datas[i]); } message.setPacketID(UUID.randomUUID().toString()); message.setBody(msg); message.setType(Type.groupchat); message.setTo(getFullRoomname(roomId)); //tjj DeliveryReceiptManager.addDeliveryReceiptRequest(message); mucMap.get(roomId).sendMessage(message); } // 发送消息,附带参数 public void sendGroupWithParms(String msg, String[] parms, Object[] datas, int chatType, String roomId) throws Exception { if (getConnection() == null) { throw new Exception("XmppException"); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); for (int i = 0; i < datas.length; i++) { message.setProperty(parms[i], datas[i]); } message.setPacketID(UUID.randomUUID().toString()); message.setBody(msg); DeliveryReceiptManager.addDeliveryReceiptRequest(message); if (chatType == ChatItem.GROUP_CHAT) { mucMap.get(roomId).sendMessage(message); // mucMap.get(roomId).sendMessage(msg); } } /** * 搜索好友 * * @param key * @return */ public List<String> searchUser(String key) { List<String> userList = new ArrayList<String>(); try { UserSearchManager search = new UserSearchManager(getConnection()); Form searchForm = search.getSearchForm("search." + Constants.SERVER_NAME); Form answerForm = searchForm.createAnswerForm(); answerForm.setAnswer("Username", true); answerForm.setAnswer("search", key); ReportedData data = search.getSearchResults(answerForm, "search." + Constants.SERVER_NAME); Iterator<Row> it = data.getRows(); Row row = null; while (it.hasNext()) { row = it.next(); userList.add(row.getValues("Username").next().toString()); } } catch (Exception e) { e.printStackTrace(); } return userList; } /** * 添加好友 无分组 * * @param userName * id * @param name * 昵称 * @return */ public boolean addUser(String userName) { if (getConnection() == null) return false; try { getConnection().getRoster().createEntry(getFullUsername(userName), getFullUsername(userName), null); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 删除好友 * * @param userName * @return */ public boolean removeUser(String userName) { if (getConnection() == null) return false; try { RosterEntry entry = null; if (userName.contains("@")) entry = getConnection().getRoster().getEntry(userName); else entry = getConnection().getRoster().getEntry(userName + "@" + getConnection().getServiceName()); if (entry == null) entry = getConnection().getRoster().getEntry(userName); getConnection().getRoster().removeEntry(entry); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 修改用户信息 * * @param file */ public boolean changeVcard(VCard vcard) { if (getConnection() == null) return false; try { // 加入这句代码,解决No VCard for ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider()); vcard.save(getConnection()); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 修改用户头像 * * @param file */ public Bitmap changeImage(File file) { Bitmap bitmap = null; if (getConnection() == null) return bitmap; try { VCard vcard = Constants.loginUser.vCard; // 加入这句代码,解决No VCard for ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider()); byte[] bytes; bytes = getFileBytes(file); String encodedImage = StringUtils.encodeBase64(bytes); // vcard.setAvatar(bytes, encodedImage); // vcard.setEncodedImage(encodedImage); // vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>" + // encodedImage + "</BINVAL>", true); vcard.setField("avatar", encodedImage); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); bitmap = FormatTools.getInstance().InputStream2Bitmap(bais); // Image image = ImageIO.read(bais); // ImageIcon ic = new ImageIcon(image); vcard.save(getConnection()); } catch (Exception e) { e.printStackTrace(); } return bitmap; } /** * 获取用户信息 * * @param user * @return */ public VCard getUserInfo(String user) { // null 时查自己 try { VCard vcard = new VCard(); // 加入这句代码,解决No VCard for ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider()); if (user == null) { vcard.load(getConnection()); } else { vcard.load(getConnection(), user + "@" + Constants.SERVER_NAME); } if (vcard != null) return vcard; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取用户头像信息 * * @param connection * @param user * @return */ public Bitmap getUserImage(String user) { // null 时查自己 ByteArrayInputStream bais = null; try { VCard vcard = new VCard(); // 加入这句代码,解决No VCard for ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp", new VCardProvider()); if (user == null) { vcard.load(getConnection()); } else { vcard.load(getConnection(), user + "@" + Constants.SERVER_NAME); } if (vcard == null || vcard.getAvatar() == null) return null; bais = new ByteArrayInputStream(vcard.getAvatar()); } catch (Exception e) { e.printStackTrace(); } if (bais == null) return null; return FormatTools.getInstance().InputStream2Bitmap(bais); } /** * 文件转字节 * * @param file * @return * @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 roomName * 房间名称 */ public MultiUserChat createRoom(String roomName) {// String user, if (getConnection() == null) return null; try { // 创建一个MultiUserChat mulChat = new MultiUserChat(getConnection(), roomName + "@conference." + getConnection().getServiceName()); // 创建聊天室 mulChat.create(roomName); // 获得聊天室的配置表单 Form form = mulChat.getConfigurationForm(); // 根据原始表单创建一个要提交的新表单。 Form submitForm = form.createAnswerForm(); // 向要提交的表单添加默认答复 for (Iterator fields = form.getFields(); fields.hasNext();) { FormField field = (FormField) fields.next(); if (!FormField.TYPE_HIDDEN.equals(field.getType()) && field.getVariable() != null) { // 设置默认值作为答复 submitForm.setDefaultAnswer(field.getVariable()); } } // 设置聊天室的新拥有者 // List<String> owners = new ArrayList<String>(); // 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",false); // // 设置进入密码 // submitForm.setAnswer("muc#roomconfig_roomsecret", password); // } // 能够发现占有者真实 JID 的角色 // submitForm.setAnswer("muc#roomconfig_whois", "anyone"); // 设置描述 submitForm.setAnswer("muc#roomconfig_roomdesc", "mulchat"); // 登录房间对话 submitForm.setAnswer("muc#roomconfig_enablelogging", true); // 仅允许注册的昵称登录 submitForm.setAnswer("x-muc#roomconfig_reservednick", false); // 允许使用者修改昵称 submitForm.setAnswer("x-muc#roomconfig_canchangenick", true); // 允许用户注册房间 submitForm.setAnswer("x-muc#roomconfig_registration", true); // 最大人数 List<String> list_single = new ArrayList<String>(); list_single.add("0"); submitForm.setAnswer("muc#roomconfig_maxusers", list_single); // 发送已完成的表单(有默认值)到服务器来配置聊天室 mulChat.sendConfigurationForm(submitForm); // muc.addMessageListener(new TaxiMultiListener()); mucMap.put(roomName, mulChat); } catch (XMPPException e) { // ToastUtil.show(MyApplication.getInstance(), "网络不给力,请重试"); Log.e("you wenti", "网络不给力,请重试" + e.getMessage()); e.printStackTrace(); return null; } return mulChat; } /** * 加入会议室 * * @param user * 昵称 * @param restart * 是否需要重启,asmack的错误。新邀请的时候为true * @param roomsName * 会议室名 */ public MultiUserChat joinMultiUserChat(String user, String roomsName, boolean restart, Date date) { if (getConnection() == null) return null; try { // 使用XMPPConnection创建一个MultiUserChat窗口 MultiUserChat muc = new MultiUserChat(getConnection(), roomsName + "@conference." + getConnection().getServiceName()); // 聊天室服务将会决定要接受的历史记录数量 DiscussionHistory history = new DiscussionHistory(); history.setMaxStanzas(99); // history.setSeconds(999999); history.setSeconds(86400); if (date == null) { } else { date = new Date(date.getTime());// 获取到后三秒的消息 这个三秒是测出来的数据 // SimpleDateFormat dateFormat = new SimpleDateFormat( // "yyyy-MM-dd HH:mm:ss SSS"); // Date date2 = dateFormat.parse("1971-12-21 07:32:34 444"); history.setSince(date); } if (roomsName.contains("307133148121090")) { System.out.println("=="); } // 用户加入聊天室 try { muc.join(user, null, history, SmackConfiguration.getPacketReplyTimeout()); } catch (Exception e) { if (Constants.IS_DEBUG) { // ToastUtil.show(MyApplication.getInstance(), "加入聊天室(" // + roomsName + ")失败" + e.toString()); android.os.Message msg = handler.obtainMessage(); msg.what = 0; msg.obj = e.getMessage(); handler.sendMessage(msg); } } muc.addParticipantStatusListener(new ParticipantStatusListener() { @Override public void voiceRevoked(String participant) { Log.i(TAG, "禁止" + participant + "发言"); } @Override public void voiceGranted(String participant) { Log.i(TAG, "给" + participant + "授权发言"); } @Override public void ownershipRevoked(String participant) { Log.i(TAG, "移除所有者权限" + participant); } @Override public void ownershipGranted(String participant) { Log.i(TAG, "授予所有者权限" + participant); } @Override public void nicknameChanged(String participant, String newNickname) { Log.i(TAG, "昵称改变了" + participant); } @Override public void moderatorRevoked(String participant) { Log.i(TAG, "移除主持人权限" + participant); } @Override public void moderatorGranted(String participant) { Log.i(TAG, "授予主持人权限" + participant); } @Override public void membershipRevoked(String participant) { Log.i(TAG, "成员权限被移除" + participant); } @Override public void membershipGranted(String participant) { Log.i(TAG, "授予成员权限" + participant); } @Override public void left(String participant) { // String lefter = participant.substring(participant // .indexOf("/") + 1); // Log.i(TAG, "执行了left方法:" + lefter + "离开的房间"); // String roomId = getRoomName(participant.substring(0, // participant.indexOf("/"))); // // 更新成员 // getChatRoomMssage(lefter, roomId); } @Override public void kicked(String participant, String actor, String reason) { Log.i(TAG, "踢人" + participant + "被踢出房间"); } @Override public void joined(String participant) { Log.i(TAG, "执行了joined方法:" + participant + "加入了房间"); // 更新成员 } @Override public void banned(String participant, String actor, String reason) { Log.i(TAG, "禁止加入房间(拉黑,不知道怎么理解,呵呵)" + participant); } @Override public void adminRevoked(String participant) { Log.i(TAG, "移除管理员权限" + participant); } @Override public void adminGranted(String participant) { Log.i(TAG, "授予管理员权限" + participant); } }); mucMap.put(roomsName, muc); if (Constants.IS_DEBUG) Log.e("muc", "会议室【" + roomsName + "】加入成功........"); return muc; } catch (Exception e) { e.printStackTrace(); if (Constants.IS_DEBUG) Log.e("muc", "会议室【" + roomsName + "】加入失败........"); return null; } finally { if (restart) { reconnect(); } } } private Handler handler = new Handler(MyApplication.getInstance().getMainLooper()) { @Override public void handleMessage(android.os.Message msg) { super.handleMessage(msg); if (msg.what == 0) { if (!"item-not-found(404)".equals((String) msg.obj)) { // ToastUtil.show(MyApplication.getInstance(), "加载聊天室失败"); } } else if (msg.what == 1) { ToastUtil.showShort(MyApplication.getInstance(), "您尚未加入该聊天室"); // luzhaosheng MyApplication.getInstance().sendBroadcast(new Intent("hasLeaveChatRoom")); // \\ } } }; /** * 离开聊天室 * * @param roomName */ public void leaveMuc(String roomName) { // 使用XMPPConnection创建一个MultiUserChat窗口 MultiUserChat muc = mucMap.get(roomName); muc.leave(); mucMap.remove(roomName); if (Constants.IS_DEBUG) Log.e("muc", "会议室【" + roomName + "】退出成功........"); } /** * 通过jid获得username * * @param fullUsername * @return */ public static String getUsername(String fullUsername) { return fullUsername.split("@")[0]; } /** * 通过username获得jid * * @param username * @return */ public static String getFullUsername(String username) { return username + "@" + Constants.SERVER_NAME; } /** * 通过roomjid获取房间名 * * @param fullRoomname * @return */ public static String getRoomName(String fullRoomname) { return fullRoomname.split("@")[0]; } /** * 通过roomjid获取发送者 * * @param fullRoomname * @return */ public static String getRoomUserName(String fullRoomname) { return fullRoomname.split("/")[1]; } /** * 通过roomName获得roomjid * * @param roomName * @return */ public static String getFullRoomname(String roomName) { return roomName + "@conference." + Constants.SERVER_NAME; } /** * 加入providers的函数 ASmack在/META-INF缺少一个smack.providers 文件 * * @param pm */ public void configureConnection(ProviderManager pm) { // Private Data Storage pm.addIQProvider("query", "jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider()); // Time try { pm.addIQProvider("query", "jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time")); } catch (ClassNotFoundException e) { Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time"); } // pm.addExtensionProvider("received", Carbon.NAMESPACE, // new Carbon.Provider()); // add delivery receipts pm.addExtensionProvider(DeliveryReceipt.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceipt.Provider()); pm.addExtensionProvider(DeliveryReceiptRequest.ELEMENT, DeliveryReceipt.NAMESPACE, new DeliveryReceiptRequest.Provider());// new DeliveryReceiptRequest().getNamespace() // add XMPP Ping (XEP-0199)5 // pm.addIQProvider("ping", "urn:xmpp:ping", new PingProvider()); // Message Events pm.addExtensionProvider("x", "jabber:x:roster", new RosterExchangeProvider()); 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.addExtensionProvider("delay", "urn:xmpp:delay", new DelayInfoProvider()); pm.addExtensionProvider("x", "jabber:x:delay", new DelayInfoProvider()); // 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()); } /** * 直接通过 HttpMime's MultipartEntity 提交数据到服务器,实现表单提交功能。 * * @return 请求所返回的内容 */ public static String requestService(String url, Map<String, String> param) { if (Constants.IS_DEBUG) Log.e("url", url); String result = ""; try { DefaultHttpClient client = getNewHttpClient(); HttpPost request = new HttpPost(url); List<NameValuePair> paramList = new ArrayList<NameValuePair>(); // if (Constants.USER_NAME!="" && !param.containsKey("userName")) { // param.put("userName", Constants.USER_NAME); // } for (Map.Entry<String, String> entry : param.entrySet()) { paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); if (Constants.IS_DEBUG) Log.e("json parm", entry.getKey() + ":" + entry.getValue()); } HttpEntity entity1 = new UrlEncodedFormEntity(paramList, "UTF-8"); request.setEntity(entity1); HttpResponse response = client.execute(request); int stateCode = response.getStatusLine().getStatusCode(); if (stateCode == 201 || stateCode == 200) { HttpEntity entity = response.getEntity(); result = EntityUtils.toString(entity, HTTP.UTF_8); if (Constants.IS_DEBUG) Log.e("json", result); } else { result = ""; } request.abort(); } catch (Exception e) { e.printStackTrace(); if (Constants.IS_DEBUG) Log.e("json", e.toString()); } finally { // 释放资源 new DefaultHttpClient().getConnectionManager().shutdown(); } return result; } private static DefaultHttpClient getNewHttpClient() { BasicHttpParams timeoutParams = new BasicHttpParams(); try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); // SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); // sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // 设置连接超时时间(单位毫秒) HttpConnectionParams.setConnectionTimeout(timeoutParams, 30000); HttpConnectionParams.setSoTimeout(timeoutParams, 150000); HttpProtocolParams.setVersion(timeoutParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(timeoutParams, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(timeoutParams, registry); return new DefaultHttpClient(ccm, timeoutParams); } catch (Exception e) { return new DefaultHttpClient(timeoutParams); } } // private boolean isFirst = true; class MUCPacketExtensionProvider implements IQProvider { @Override public IQ parseIQ(XmlPullParser parser) throws Exception { int eventType = parser.getEventType(); myRooms.clear(); leaveRooms.clear(); // if (!isFirst) { // XmppConnection.getInstance().closeConnection(); // } // isFirst = false; Room info = null; while (true) { if (eventType == XmlPullParser.START_TAG) { if ("room".equals(parser.getName())) { String account = parser.getAttributeValue("", "account"); String roomName = parser.getAttributeValue("", "roomName"); String roomJid = parser.getAttributeValue("", "roomJid"); info = new Room(); info.name = roomName; info.roomid = roomJid; myRooms.add(info); } if ("friend".equals(parser.getName())) { info.friendList.add(XmppConnection.getUsername(parser.nextText())); } } else if (eventType == XmlPullParser.END_TAG) { if ("muc".equals(parser.getName())) { break; } } eventType = parser.next(); } return null; } } /** * 初始化聊服务会议列表 */ private ArrayList<HostedRoom> initHostRoom() { ArrayList<HostedRoom> roominfos = new ArrayList<HostedRoom>(); Collection<HostedRoom> hostrooms; try { hostrooms = MultiUserChat.getHostedRooms(getConnection(), Constants.SERVER_NAME); for (HostedRoom entry : hostrooms) { roominfos.add(entry); // Log.i("aaa", // "名字:" + entry.getName() + " - ID:" + entry.getJid()); } // Log.i("aaa", "服务会议数量:" + roominfos.size()); } catch (XMPPException e) { e.printStackTrace(); } if (roominfos.size() > 0) { return roominfos; } return null; } /** * 获取聊天室的所有成员 * * @return */ public List<Friend> getChatRoomMember(String roomName) { final List<Friend> roomnumber = new ArrayList<Friend>(); MultiUserChat muc = new MultiUserChat(connection, getFullRoomname(roomName)); Iterator<String> it = muc.getOccupants(); while (it.hasNext()) { String name = it.next(); name = name.substring(name.indexOf("/") + 1); roomnumber.add(new Friend(name)); Log.i("aaa", "成员名字;" + name); } return roomnumber; } /** * 获取已经加入的聊天室 */ public void getJoinedRoom() { System.out.println("--------------------------------------"); Iterator<?> joinedRooms = MultiUserChat.getJoinedRooms(getConnection(), initHostRoom().get(2).getJid()); while (joinedRooms.hasNext()) { System.out.println(joinedRooms); joinedRooms.next(); } System.out.println("--------------------------------------"); } /** * 获取管理员列表 */ public void getAdmins() { try { Collection<Affiliate> affiliates = mulChat.getAdmins(); Iterator<Affiliate> iterator = affiliates.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (XMPPException e) { e.printStackTrace(); } } /** * 邀请进入群聊 * * @param ofUserid * @param string */ public void invite(String roomId, String ofUserid, String reason) { MultiUserChat multiUserChat = mucMap.get(roomId); multiUserChat.invite(getFullUsername(ofUserid), DateUtil.now_yyyy_MM_dd_HH_mm_ss_SSS()); } /** * 移除聊天室人员 * * @param string */ public void removeChatRoomMember(String ofuserid, String roomId) { // MultiUserChat multiUserChat = mucMap.get(roomId); // try { try { sendMsgWithParms("KickParticipant", new String[] { "KickParticipant" }, new Object[] { ofuserid }, 1, roomId); org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); message.setProperty("KickParticipant", ofuserid); message.setProperty("roomid", roomId); message.setBody("KickParticipant"); ChatManager cm = XmppConnection.getInstance().getConnection().getChatManager(); // 发送消息给pc服务器的好友(获取自己的服务器,和好友) Chat removeChat = cm.createChat(getFullUsername(ofuserid), null); removeChat.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } // multiUserChat.kickParticipant(getFullUsername(ofuserid), "踢了"); // } catch (XMPPException e) { // e.printStackTrace(); // } } }
转载请注明原文地址: https://www.6miu.com/read-31641.html

最新回复(0)