其他分享
首页 > 其他分享> > Android smack 工具类(包含连接及相关方法)

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

作者:互联网

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;
		}
	};

	

}

 

标签:return,mXMPPConnection,Presence,smack,static,new,Android,null,连接
来源: https://blog.csdn.net/lhy24680/article/details/113371192