Android studio使用smack连接xmpp服务器收发消息

    我使用的是ejabberd16.09的linux版本,安装教程网上有很多,我在这里只介绍一下android端连接、登录和收发消息的方法。文章最后附上了我写的一个demo,欢迎大家参考。

ejabberd官网地址:点击打开链接

    进入正题,我使用的是smack4.1.2包,需要在android studio的build.gradle文件中加入

    compile ("org.igniterealtime.smack:smack-android-extensions:4.1.2") {
        exclude group: 'xpp3', module: 'xpp3'
    }
    compile ("org.igniterealtime.smack:smack-android:4.1.2") {
        exclude group: 'xpp3', module: 'xpp3'
    }
    // Optional for XMPPTCPConnection
    compile ("org.igniterealtime.smack:smack-tcp:4.1.2") {
        exclude group: 'xpp3', module: 'xpp3'
    }
    // Optional for XMPP-IM (RFC 6121) support (Roster, Threaded Chats, …)
    compile ("org.igniterealtime.smack:smack-im:4.1.2") {
        exclude group: 'xpp3', module: 'xpp3'
    }

点击 "Sync Project with Gradle Files"按钮即可将smack4.1.2引入项目中


下面介绍连接和登录的方法,并带有监听收到消息的方法

     private XMPPTCPConnection con;
     private Runnable XmppThread = new Runnable(){
	@Override
        public void run() {
            boolean tag = false;
            XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
            config.setHost("192.168.26.38");              //设置ejabberd主机IP
            config.setServiceName("h.com");         //设置ejabberd服务器名称
            config.setPort(5222);                   //设置端口号:默认5222
            config.setUsernameAndPassword("admin", "111111");    //设置用户名与密码
            config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);      //禁用SSL连接
            config.setSendPresence(true);
            config.setDebuggerEnabled(true);
            con = new XMPPTCPConnection(config.build());
            try {
                con.connect();
                tag = con.isConnected();
                Roster roster = Roster.getInstanceFor(con);
                try {
                    con.login();
                    Log.e("TAG", "login sucess!!");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //         设置聊天监听器,监听聊天消息
                ChatManager chatm = ChatManager.getInstanceFor(con);
                chatm.addChatListener(new ChatManagerListener() {
                    @Override
                    public void chatCreated(Chat chat, boolean b) {
                        if (!b) {           //不是本地创建的会话
                            chat.addMessageListener(new ChatMessageListener() {
                                @Override
                                public void processMessage(Chat chat, Message message) {
                                    Log.d("PushTest", message.toString());
                                    Log.d("PushTest", message.getType().toString());
                                    Log.d("PushTest", message.getExtension("extension").toString());
                                    Log.d("PushTest", message.getExtension("extension").getNamespace());
                                    Log.d("PushTest", message.getExtension("extension").getElementName());
                                    DefaultExtensionElement defaultExtensionElement = message.getExtension(
                                            ELEMENT_NAME,NAME_SPACE);
                                    String name = defaultExtensionElement.getValue("name");
                                    String url = defaultExtensionElement.getValue("url");
                                    Log.d("PushTest", name);
                                    Log.d("PushTest", url);
                                }
                            });
                        }
                    }
                });

            } catch (Exception e) {
                Log.e("TAG", "connect failed!" + e.toString());
                e.printStackTrace();

            }
            if(tag){
                handler.sendEmptyMessage(0x00);
            }else{
                handler.sendEmptyMessage(0x01);
            }
        }
    };



其中的

                                    DefaultExtensionElement defaultExtensionElement = message.getExtension(
                                            ELEMENT_NAME,NAME_SPACE);
                                    String name = defaultExtensionElement.getValue("name");
                                    String url = defaultExtensionElement.getValue("url");

是我在服务端发送消息时加的Message的属性拓展,定义如下:

import org.jivesoftware.smack.packet.ExtensionElement;

public class Received implements ExtensionElement  {
{
	
	private static final String NAME_SPACE = "extension";
	private static final String ELEMENT_NAME = "userinfo";
	
    //用户姓名元素名称
    private String nameElement = "name";
    //用户姓名元素文本(对外开放)
    private String nameText = "";

    //用户地址元素名称
    private String urlElement = "url";    
    //用户地址元素文本(对外开放)
    private String urlText = "";

	@Override
	public String getElementName() {
		return ELEMENT_NAME;
	}

	@Override
	public String getNamespace() {
		return NAME_SPACE;
	}

	@Override
	public CharSequence toXML() {
		StringBuilder sb = new StringBuilder();

        sb.append("<").append(ELEMENT_NAME).append(" xmlns=\"").append(NAME_SPACE).append("\">");
        sb.append("<" + nameElement + ">").append(nameText).append("");
        sb.append("<" + urlElement + ">").append(urlText).append("");
        sb.append("");

        return sb.toString();
	}

	public String getNameText() {
		return nameText;
	}

	public void setNameText(String nameText) {
		this.nameText = nameText;
	}

	public String getUrlText() {
		return urlText;
	}

	public void setUrlText(String urlText) {
		this.urlText = urlText;
	}
}
使用时的方法如下:

		ChatManager chatm = ChatManager.getInstanceFor(mXmppConnection);
		Chat chat = chatm.createChat("[email protected]", new ChatMessageListener() {        //创建与ly的会话
            public void processMessage(Chat chat, Message message) {
                System.out.println("Received message: " + message);
            }
            });
		try {
		    /**
		     * 发送一条消息给ly
		     */
			Received received = new Received();
			received.setNameText(name);
				Message message = new Message();
				message.setBody(context);
				message.setTo("[email protected]");
				message.setFrom("[email protected]");
				message.addExtension(received);
				chat.sendMessage(message);

		} catch (SmackException.NotConnectedException e) {
		    e.printStackTrace();
		}


我写了一个小demo,欢迎大家指出不足之处!

Android使用smack连接ejabberd服务器注册、收发消息


你可能感兴趣的:(android)