Android smack 工具类(包含连接及相关方法)

Android smack 工具类(包含连接及相关方法),第1张

概述publicclassXmppUtil{ /** *XMPP连接 */ privatestaticXMPPTCPConnectionmXMPPConnection; /** *单聊管理器 */ privatestaticChatManagermChatManager; /** *smackpingopenfire管理器 */ privatestaticPingManagermPingManager; /**
public class XmppUtil {	/**	 * XMPP连接	 */	private static XMPPTCPConnection mXMPPConnection;	/**	 * 单聊管理器	 */	private static ChatManager mChatManager;	/**	 * smack Ping openfire管理器	 */	private static PingManager mPingManager;	/**	 * 群聊管理器	 */	private static MultiUserChatManager multiUserChatManager;	/**	 * XMPP连接监听	 */	private static CheckConnectionListener checkConnectionListener;	/**	 * smack Ping openfire失败监听	 */	private static PingServerFailedListener PingServerFailedListener;	/**	 * 单聊接收监听	 */	private static MsgListener msgListener;	/**	 * 单聊发送监听	 */	private static OutChatListener mOutChatListener;	/**	 * 监听邀请加入聊天室	 */	private static MucInvitationListener mucInvitationListener;	/**	 * 好友状态更新监听	 */	private static FrIEndsPacketListener frIEndsPacketListener;	static {		try {			Class.forname("org.jivesoftware.smack.ReconnectionManager");		} catch (Exception e) {			e.printstacktrace();		}	}	/**	 *	 * @return XMPPConnection是否连接并登陆	 */	public static boolean xmppIsConncetedAndLogin() {		return mXMPPConnection != null && mXMPPConnection.isConnected() && mXMPPConnection.isAuthenticated();	}	/**	 * 初始化XMPPConnection并建立连接	 */	public static synchronized voID initXMPP() {		// 已经连接并登陆上		if (xmppIsConncetedAndLogin()) {			return;		} else {//			disconnect(); // 先断开连接			initXMPPConfig();			connectXMPP();		}	}	private static voID initXMPPConfig() {		try {			SmackConfiguration.DEBUG = true;			// 配置XmppConnection			XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()					.setHostAddress(InetAddress.getByname(Const.XMPP_HOST)) // 设置openfire主机IP					.setXmppDomain(Const.XMPP_DOMAIN)					.setHost(Const.XMPP_HOST)					.setPort(Const.XMPP_PORT)					.setSecurityMode(ConnectionConfiguration.SecurityMode.Disabled) //禁用SSL连接					.setCompressionEnabled(false)					.setSendPresence(false) // 先设离线获取离线消息后再设在线					.setCompressionEnabled(true) // 设置开启压缩,可以节省流量					.setConnectTimeout(30000)					.build();			// 收到好友邀请后manual表示需要经过同意,accept_all表示不经同意自动为好友			Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.accept_all);			mXMPPConnection = new XMPPTCPConnection(config);			//开启重联机制			ReconnectionManager mReconnectionManager = ReconnectionManager.getInstanceFor(mXMPPConnection);//			mReconnectionManager.setFixedDelay(5);			mReconnectionManager.enableautomaticReconnection();		} catch (Exception e) {			AppLog.deBUG(XmppUtil.class, "XMPP 配置失败---" + e.getMessage());		}	}	/**	 * 连接XMPP	 */	public static voID connectXMPP() {		try {			mXMPPConnection.connect();			AppLog.deBUG(XmppUtil.class, "XMPP连接结果---" + mXMPPConnection.isConnected());			// 使用所有用户统一密码123,需要含参数Resourcepart.from("Smack"),不然每次自动分配一个名字,导致掉线重连的话在openfire看连接名称会变			mXMPPConnection.login(UserConfig.getUserID(), "123", Resourcepart.from("Smack"));			if(mXMPPConnection.isAuthenticated()){				AppLog.deBUG(XmppUtil.class, "loginXMPP---success");				broadcastUtil.sendLoginbroadcast(true, false);				//登录成功,设置用户的vcard信息,这个是为了记录昵称,可以不要				VCard vCard = new VCard();				vCard.setNickname(UserConfig.user.getname());				VCardManager.getInstanceFor(mXMPPConnection).saveVCard(vCard);				// 获取离线信息				getofflineMessage();				//设置上线				setPresence(0);//设置在线状态				// 设置各种监听				addListener();			} else {				AppLog.deBUG(XmppUtil.class, "loginXMPP----fail");//				initXMPP();			}		} catch (Exception e) {			AppLog.deBUG(XmppUtil.class, "XMPP connect--Exception---" + e.getMessage());//			initXMPP();		}	}	/**	 * 添加各种监听	 */	private static voID addListener() {		//添加xmpp连接监听		if (checkConnectionListener == null) {			checkConnectionListener = new CheckConnectionListener();		}		mXMPPConnection.addConnectionListener(checkConnectionListener);		// 添加聊天信息监听		mChatManager = ChatManager.getInstanceFor(mXMPPConnection);		if (msgListener == null) {			msgListener = new MsgListener();		}		mChatManager.addIncomingListener(msgListener);		// 单聊发出监听,估计是对方接收到了才会返回监听,发送是不会返回监听的//		if (mOutChatListener == null) {//			mOutChatListener = new OutChatListener();//		}//		mChatManager.addOutgoingListener(mOutChatListener);		//监听邀请加入聊天室请求		multiUserChatManager = MultiUserChatManager.getInstanceFor(mXMPPConnection);		if (mucInvitationListener == null) {			mucInvitationListener = new MucInvitationListener();		}		multiUserChatManager.addInvitationListener(mucInvitationListener);		// 注册好友状态更新监听		if (frIEndsPacketListener == null) {			frIEndsPacketListener = new FrIEndsPacketListener();		}		StanzaFilter filter = new AndFilter();		mXMPPConnection.addAsyncStanzaListener(frIEndsPacketListener, filter);		// 自定义IQ请求获取群成员时,需要这个监听接收返回数据,请求在requireMatchUser()		ProvIDerManager.addIQProvIDer(TAG_INFO, INFO_nameSPACE, new ResponseAllMucmemberIQProvIDer());		// 默认Ping间隔 设为180秒		mPingManager = PingManager.getInstanceFor(mXMPPConnection);		mPingManager.setPingInterval(180);		if (PingServerFailedListener == null) {			PingServerFailedListener = new PingServerFailedListener();		}		mPingManager.registerPingFailedListener(PingServerFailedListener);	}	/**	 * 获取离线消息	 *	 * @return	 */	private static Map<String, List<HashMap<String, String>>> getofflineMessage() {		if (mXMPPConnection == null) {			return null;		}		Map<String, List<HashMap<String, String>>> offlineMsgs = null;		try {			OfflineMessageManager offlineManager = new OfflineMessageManager(mXMPPConnection);			List<Message> messageList = offlineManager.getMessages();			int count = offlineManager.getMessageCount();			if (count <= 0) {				return null;			}			offlineMsgs = new HashMap<>();			for (Message message : messageList) {				// Todo 根据实际处理			}			offlineManager.deleteMessages();		} catch (Exception e) {			AppLog.deBUG(XmppUtil.class, "---getofflineMessage---" + e.getMessage());		}		return offlineMsgs;	}	public static voID disconnect() {		if (mXMPPConnection != null) {			// 移除连接监听			/*if (checkConnectionListener != null) {				mXMPPConnection.removeConnectionListener(checkConnectionListener);			}			if (mPingManager != null && PingServerFailedListener != null) {				mPingManager.unregisterPingFailedListener(PingServerFailedListener);//				mPingManager = null;			}			if (mChatManager != null && msgListener != null) {				mChatManager.removeListener(msgListener);//				mChatManager = null;			}			if (multiUserChatManager != null && mucInvitationListener != null) {				multiUserChatManager.removeInvitationListener(mucInvitationListener);//				multiUserChatManager = null;			}*/			if (mXMPPConnection.isConnected()) {				mXMPPConnection.disconnect();				mXMPPConnection = null;			}		}	}    	 /**      * 更改用户状态      */      public static voID setPresence(int code) {        Presence presence=null;        try {			switch (code) {			case 0:				presence = new Presence(Presence.Type.available);  //在线				break;			case 1:				presence = new Presence(Presence.Type.available);  //设置Q我吧				presence.setMode(Presence.Mode.chat);				break;			case 2:                                                                                      //隐身//				Roster roster = Roster.getInstanceFor(mXMPPConnection);//				Collection<RosterEntry> entrIEs = roster.getEntrIEs();//				for (RosterEntry entry : entrIEs) {//					presence = new Presence(Presence.Type.unavailable);//					presence.setPacketID(Packet.ID_NOT_AVAILABLE);//					presence.setFrom(mXMPPConnection.getUser());//					presence.setTo(entry.getUser());//				}//				// 向同一用户的其他客户端发送隐身状态//				presence = new Presence(Presence.Type.unavailable);//				presence.setPacketID(Packet.ID_NOT_AVAILABLE);//				presence.setFrom(mXMPPConnection.getUser());//				presence.setTo(StringUtils.parsebareAddress(mXMPPConnection.getUser()));				break;			case 3:				presence = new Presence(Presence.Type.available);  //设置忙碌				presence.setMode(Presence.Mode.dnd);				break;			case 4:				presence = new Presence(Presence.Type.available);  //设置离开				presence.setMode(Presence.Mode.away);				break;			case 5:				presence = new Presence(Presence.Type.unavailable);  //离线				break;			default:				break;			}			if(presence!=null){				mXMPPConnection.sendStanza(presence);			}		} catch (SmackException.NotConnectedException | InterruptedException e) {			AppLog.deBUG(XmppUtil.class, "setPresence---" + e.getMessage());		}    }  	/**      * 删除当前用户      * @param connection      * @return      */      public static boolean deleteAccount(XMPPConnection connection) {		if (mXMPPConnection == null)			return false;		try {			AccountManager.getInstance(connection).deleteAccount();			return true;		} catch (XMPPException | SmackException | InterruptedException e) {			e.printstacktrace();			return false;		}	}	/**	 * 返回所有组信息 <RosterGroup>	 * @return List(RosterGroup)	 */	public static List<RosterGroup> getGroups() {		if (mXMPPConnection == null) {			return null;		}		List<RosterGroup> groupsList = new ArrayList<RosterGroup>();		Collection<RosterGroup> rosterGroup = Roster.getInstanceFor(mXMPPConnection).getGroups();		Iterator<RosterGroup> i = rosterGroup.iterator();		while (i.hasNext())			groupsList.add(i.next());		return groupsList;	}	/**	 * 返回相应(groupname)组里的所有用户<RosterEntry>	 * @return List(RosterEntry)	 */	public static List<RosterEntry> getEntrIEsByGroup(String groupname) {		if (mXMPPConnection == null) {			return null;		}		List<RosterEntry> EntrIEsList = new ArrayList<>();		RosterGroup rosterGroup = Roster.getInstanceFor(mXMPPConnection).getGroup(groupname);		Collection<RosterEntry> rosterEntry = rosterGroup.getEntrIEs();		for (RosterEntry aRosterEntry : rosterEntry) {			EntrIEsList.add(aRosterEntry);		}		return EntrIEsList;	}	/**	 * 获取所有好友信息	 *	 * @return List<RosterEntry>	 */	public List<RosterEntry> getAllEntrIEs() {		if (mXMPPConnection == null) {			return null;		}		List<RosterEntry> EnList = new ArrayList<>();		Collection<RosterEntry> rosterEntry = Roster.getInstanceFor(mXMPPConnection).getEntrIEs();		for (RosterEntry aRosterEntry : rosterEntry) {			EnList.add(aRosterEntry);		}		return EnList;	}			/**      * 创建一个组      */ 	public static boolean addGroup(String groupname)    {          try {			Roster.getInstanceFor(mXMPPConnection).createGroup(groupname);            return true;          } catch (Exception e) {              e.printstacktrace();              Log.e("jj", "创建分组异常:"+e.getMessage());            return false;          }      }            /**      * 删除一个组      */      public static boolean removeGroup(Roster roster,String groupname)      {          return false;      }	/**	 * 添加好友 无分组	 *	 * @param username username	 * @param name     name	 * @return boolean	 */	public static boolean addUser(String username,String name) {		if (mXMPPConnection == null) {			return false;		}		try {			Roster.getInstanceFor(mXMPPConnection).createEntry(					JIDCreate.entitybareFrom(username), name, null);			return true;		} catch (Exception e) {			e.printstacktrace();			return false;		}			}	/**	 * 添加好友 有分组	 *	 * @param name      name	 * @param groupname groupname	 * @return boolean	 */	public static boolean addUsers(String username, String name,String groupname)	{		try {			Presence subscription = new Presence(Presence.Type.subscribed);			subscription.setTo(JIDCreate.entitybareFrom(username));			username += "@" + mXMPPConnection.getServicename();			mXMPPConnection.sendStanza(subscription);			Roster.getInstanceFor(mXMPPConnection).createEntry(JIDCreate.entitybareFrom(username), name,					new String[]{groupname});			return true;		} catch (Exception e) {			e.printstacktrace();			Log.e("jj", "添加好友异常:"+e.getMessage());			return false;		}			}	/**	 * 删除好友	 *	 * @param username username	 * @return boolean	 */	public boolean removeUser(String username) {		if (mXMPPConnection == null)			return false;		try {			RosterEntry entry = null;			if (username.contains("@")) {				entry = Roster.getInstanceFor(mXMPPConnection).getEntry(JIDCreate.entitybareFrom(username));			} else {				entry = Roster.getInstanceFor(mXMPPConnection).getEntry(JIDCreate.entitybareFrom(						username + "@" + mXMPPConnection.getServicename()));			}			if (entry == null) {				entry = Roster.getInstanceFor(mXMPPConnection).getEntry(JIDCreate.entitybareFrom(username));			}			Roster.getInstanceFor(mXMPPConnection).removeEntry(entry);			return true;		} catch (Exception e) {			e.printstacktrace();			return false;		}	}		/**     * 把一个好友添加到一个组中     * @param userJID     * @param groupname     */    public static voID addUserToGroup(final String userJID, final String groupname) {			try {				RosterGroup group = Roster.getInstanceFor(mXMPPConnection).getGroup(groupname);				// 这个组已经存在就添加到这个组,不存在创建一个组				RosterEntry entry = Roster.getInstanceFor(mXMPPConnection).getEntry(JIDCreate.bareFrom(userJID));				if (group != null) {					if (entry != null)						group.addEntry(entry);				} else {					RosterGroup newGroup = Roster.getInstanceFor(mXMPPConnection).createGroup("我的好友");					if (entry != null)						newGroup.addEntry(entry);				}			} catch (Exception e) {				e.printstacktrace();			}    }    /**     * 把一个好友从组中删除     * @param userJID     * @param groupname     */    public static voID removeUserFromGroup(final String userJID,final String groupname) {            RosterGroup group = Roster.getInstanceFor(mXMPPConnection).getGroup(groupname);            if (group != null) {                try {                	RosterEntry entry = Roster.getInstanceFor(mXMPPConnection).getEntry(JIDCreate.bareFrom(userJID));                    if (entry != null)                        group.removeEntry(entry);                } catch (Exception e) {                    e.printstacktrace();                }            }     }        /**      * 修改签名     */      public static voID changeSign(int code , String content){    	try {			Presence presence = getonlinestatus(code);			presence.setStatus(content);			mXMPPConnection.sendStanza(presence);		} catch (Exception e) {			AppLog.deBUG(XmppUtil.class, "changeSign---" + e.getMessage());		}    }            /**	 * 发送消息	 * @param content	 * @param touser	 * @throws XMPPException	 */	public static voID sendMessage(String content, String touser) throws XmppStringprepException,			SmackException.NotConnectedException, InterruptedException{		if(mXMPPConnection == null || !mXMPPConnection.isConnected() || !mXMPPConnection.isAuthenticated()){			throw new SmackException.NotConnectedException();		}//		ChatManager chatmanager = mXMPPConnection.getChatManager();        Chat chat = ChatManager.getInstanceFor(mXMPPConnection).				chatWith(JIDCreate.entitybareFrom(touser + "@" + Const.XMPP_DOMAIN));		if (chat != null) {			chat.send(content);			Log.e("jj", "发送成功");		}	}		public static voID setonlinestatus(ImageVIEw iv_stutas,int code,TextVIEw tv_stutas,String[] items ){		switch (code) {		case 0://在线			iv_stutas.setimageResource(R.drawable.func_chat_person_status_evk);			tv_stutas.setText(items[0]);			break;		case 1://q我吧			iv_stutas.setimageResource(R.drawable.func_chat_person_status_evm);			tv_stutas.setText(items[1]);			break;		case 2://隐身			iv_stutas.setimageResource(R.drawable.func_chat_person_status_evf);			tv_stutas.setText(items[2]);			break;		case 3://忙碌			iv_stutas.setimageResource(R.drawable.func_chat_person_status_evd);			tv_stutas.setText(items[3]);			break;		case 4://离开			iv_stutas.setimageResource(R.drawable.func_chat_person_status_evp);			tv_stutas.setText(items[4]);			break;		default:			break;		}			}		public static Presence getonlinestatus(int code){		Presence presence=null;		  switch (code) {  	        case 0:  	            presence = new Presence(Presence.Type.available);  //在线	            break;  	        case 1:  	            presence = new Presence(Presence.Type.available);  //设置Q我吧	            presence.setMode(Presence.Mode.chat);  	            break;  	        case 2:                                                                                      //隐身	            presence = new Presence(Presence.Type.unavailable);  	            break;  	        case 3:  	            presence = new Presence(Presence.Type.available);  //设置忙碌	            presence.setMode(Presence.Mode.dnd);  	            break;  	        case 4:  	            presence = new Presence(Presence.Type.available);  //设置离开	            presence.setMode(Presence.Mode.away);  	            break;  	        case 5:  	            presence = new Presence(Presence.Type.unavailable);  //离线	            break;  	        default:  	            break;  	        }  		return presence;	}	/**	 * 创建聊组	 * @param user 用户ID	 * @param roomname 房间名	 * @param password 房间密码	 * @return	 */	public static MultiUserChat createRoom(String user, String roomname, String password){		if (mXMPPConnection == null){			return null;		}		MultiUserChat muc = null;		try {			// 创建一个MultiUserChat 参数(XmppConnection,群全称)			muc = MultiUserChatManager.getInstanceFor(mXMPPConnection)					.getMultiUserChat(JIDCreate.entitybareFrom(roomname					+ "@conference." + mXMPPConnection.getServicename()));			// 创建聊天室			muc.create(Resourcepart.from(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(mXMPPConnection.getUser().asEntitybareJIDString()); // 用户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);			//允许占有者更改主题			submitForm.setAnswer("muc#roomconfig_changesubject",true);			//设置房间最大用户数			List<String> maxusers = new ArrayList<String>();			maxusers.add("50");			submitForm.setAnswer("muc#roomconfig_maxusers", maxusers);			if (!password.equals("123")) {				// 进入是否需要密码				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();			muc = null;		}		return muc;	}	/**	 * 加入聊天室	 * @param user 用户名,不是jID,例如:用户66@192.168.1.1,是前面的66	 * @param password 房间的密码	 * @param roomsname 房间的名字	 */	public static MultiUserChat joinMultiUserChat(String user, String password, String roomsname) {		try {			// 使用XMPPConnection创建一个MultiUserChat窗口			MultiUserChat muc = MultiUserChatManager.getInstanceFor(mXMPPConnection)					.getMultiUserChat(JIDCreate.entitybareFrom(roomsname							+ "@conference." + mXMPPConnection.getServicename()));			// 聊天室配置			MucEnterConfiguration.Builder builder = muc.getEnterConfigurationBuilder(Resourcepart.from(user));			builder.withPassword(password);			// 加入时不发送历史//			builder.requestNoHistory();			// 加入时发送99条历史,为了获取离线群消息,保存时会去重,这种方案也有弊端			builder.requestMaxStanzasHistory(99);			MucEnterConfiguration mMucEnterConfiguration = builder.build();			// 用户加入聊天室 参数()			muc.join(mMucEnterConfiguration);			System.out.println("会议室加入成功........");			return muc;		} catch (XMPPException | XmppStringprepException | InterruptedException | SmackException e) {			e.printstacktrace();			System.out.println("会议室加入失败........");			//muc = null;			return null;		}	}	/**	 * 获取用户VCard信息	 * @param user 为jID 如:123@localhost tuo	 * @return	 * @throws XMPPException	 */	public static VCard getUserVCard(String user) {		if (mXMPPConnection == null) {			return null;		}		VCard vcard = new VCard();		try {			vcard = VCardManager.getInstanceFor(mXMPPConnection).loadVCard(JIDCreate.entitybareFrom(user));		} catch (Exception e) {			e.printstacktrace();		}		return vcard;	}	/**	 * 遍历每个人所创建的群	 * @return 遍历每个人所创建的群	 * @throws XMPPException XMPPException	 */	public static List<HostedRoom> getHostedRooms() throws XMPPException{		if (mXMPPConnection == null) {			return null;		}		Collection<HostedRoom> hostrooms;		List<HostedRoom> roominfos = new ArrayList<>();		try {			hostrooms = MultiUserChatManager.getInstanceFor(mXMPPConnection)					.getHostedRooms(JIDCreate.domainbareFrom("@conference." + mXMPPConnection.getServicename()));			for (HostedRoom entry : hostrooms) {				roominfos.add(entry);				Log.i("room", "名字:" + entry.getname() + " - ID:" + entry.getJID());			}			Log.i("room", "服务会议数量:" + roominfos.size());		} catch (XMPPException | XmppStringprepException | InterruptedException | SmackException e) {			e.printstacktrace();			return null;		}		return roominfos;	}	/**	 * 获取人员花名册	 * @return 人员花名册	 */	public static Roster getRoster () {		return Roster.getInstanceFor(mXMPPConnection);	}	/**	 * 获取XMPPConnection服务名字	 * @return MPPConnection服务名字	 */	public static DomainbareJID getXMPPConnectionServicename() {		return mXMPPConnection.getServicename();	}	/**	 * 请求时XML的子节点名字	 */	public static final String TAG_INFO = "info";	/**	 * openfire插件名字	 */	public static final String MATCH_USER_PLUGIN_name = "getMucAllMember";	/**	 * 请求时携带的类型,可以理解为接口名	 */	public static final String GET_MUC_ALL_MEMBERS = "get_muc_all_members";	/**	 * 请求的空间名	 */	public static  final  String INFO_nameSPACE = "match:iq:info";	/**	 * 请求获取群所有成员,需要配合openfire插件mucPlugin和getMucAllMember一起使用	 * 自定义请求第一步,第二步在RequestAllMucmemberByRoomJIDIQ	 * 这个请求需要在xmpp连接时增加ProvIDerManager.addIQProvIDer(TAG_INFO, INFO_nameSPACE, new ResponseAllMucmemberIQProvIDer());	 * @param roomname 群名称,建群时那个(openfire服务器ofmucroom表中的name字段)	 */	public static voID requireMatchUser(String roomname){		try {			RequestAllMucmemberByRoomJIDIQ msg = new RequestAllMucmemberByRoomJIDIQ(TAG_INFO);			// 谁请求的			msg.setFrom(mXMPPConnection.getUser());			// 发送给openfire的哪个插件,MATCH_USER_PLUGIN_name是插件的名称			msg.setTo(JIDCreate.from(mXMPPConnection.getServicename() + "/" + MATCH_USER_PLUGIN_name));			msg.setData(roomname);			msg.setMsgType(GET_MUC_ALL_MEMBERS);			mXMPPConnection.sendStanza(msg);			// 增加过滤限制,只接收这个号发送出去的RequestAllMucmemberByRoomJIDIQ请求			StanzaFilter filter = new AndFilter( new StanzaTypeFilter(RequestAllMucmemberByRoomJIDIQ.class),					ToMatchesFilter.create(mXMPPConnection.getUser()));			mXMPPConnection.addSyncStanzaListener(stanzaListener,filter);			mXMPPConnection.addSyncStanzaListener(errorStanzaListener,errorFilter);		} catch (Exception e) {			// Todo auto-generated catch block			e.printstacktrace();			AppLog.deBUG(XmppUtil.class, "获取群成员-----" + e.getMessage());		}	}	/**	 * 自定义请求的返回监听	 */	private static StanzaListener stanzaListener = new StanzaListener() {		@OverrIDe		public voID processstanza(Stanza packet) {			// Todo auto-generated method stub			RequestAllMucmemberByRoomJIDIQ iq = (RequestAllMucmemberByRoomJIDIQ)packet;			String roomname = iq.getData();			List<Child> childList = iq.getChildList();			MucUtil.mucmembers.put(roomname, childList);			// 发送获取群聊成员完成广播			MucAllMembersReceive mucAllMembersReceive = new MucAllMembersReceive();			mucAllMembersReceive.setRoomname(roomname);			mucAllMembersReceive.setChildList(childList);			EventBus.getDefault().post(mucAllMembersReceive);		}	};	/**	 * 错误	 */	private static StanzaListener errorStanzaListener = new StanzaListener() {		@OverrIDe		public voID processstanza(Stanza packet) {			// Todo auto-generated method stub			RequestAllMucmemberByRoomJIDIQ iq = (RequestAllMucmemberByRoomJIDIQ)packet;		}	};	/**	 * 错误过滤器	 */	private static StanzaFilter errorFilter = new StanzaFilter() {		@OverrIDe		public boolean accept(Stanza stanza) {			if(stanza instanceof IQ)			{				if (((IQ) stanza).getType().equals("error"))					return true;			}			return  false;		}	};	}

 

总结

以上是内存溢出为你收集整理的Android smack 工具类包含连接及相关方法)全部内容,希望文章能够帮你解决Android smack 工具类(包含连接及相关方法)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1051274.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存