Asmack-based Chat

Source: Internet
Author: User

Now the function of the chat module is basically used in many projects, some of the implementation of the chat is native (native) some are based on the third-party SDK such as cloud, ring letter and so on. Native development is a bit more difficult and workload-intensive, but flexibility and maintainability are simple. The advantage of third-party instant messaging is that rapid integration and development greatly reduces the difficulty and time period of development.

Here is the native development IM for chat based on Openfire+asmack implementations. In the next step I will launch an instant messaging development based on the Melt Cloud SDK.

Source of the download, chat is one of the modules in the Wechar package in the other code to ignore the good.

SOURCE download

GitHub Download


Environment installation

OpenFire Installation and configuration includes creating a room to add users, spark installation here does not do a detailed explanation of Baidu resources a lot.

Connect to a server, log in, join a chat room

Here's the code to do three things

/** * 1, connect the server * 2, login * 3, join the group chat  * */
Linked server
<em> </em>connectionconfiguration connectionconfiguration = new Connectionconfiguration ("125.65.82.216" , 5222, "125.65.82.216");                Xmppconnection xmppconnection = new Xmppconnection (connectionconfiguration);                try {                    //link server                    connectionconfiguration.setreconnectionallowed (true);                    Xmppconnection.connect ();} catch (Xmppexception e) {                    e.printstacktrace ();                    LOG.I ("ERROR", E + "");                }
here the following code to explain, the next three singular, the IP address, the port number (generally 5222), the name of the server is set up OpenFire when named, pay attention to build openfire here as far as possible in the local area network build otherwise always link not server
Connectionconfiguration connectionconfiguration = new Connectionconfiguration ("125.65.82.216", 5222, "125.65.82.216" );

Sign in and join a chat room
if (xmppconnection.isconnected ()) {                        log.i ("LOGIN", "Join succeeded");                        Login                        xmppconnection.login ("Bruse", "123");                        Join Group chat                        multiuserchat = new Multiuserchat (xmppconnection, "[email protected]");                        Nickname Multiuserchat.join after affiliation                        ("Bruse");}
Here's the name of the room, note that after adding @conference.xxx, in Spark can see the corresponding room name
[Email protected]
If you join the room, you will be prompted as follows
Send Message
Use the message class in the Asmack framework to encapsulate messages, sender, recipient, message type (group chat, single chat), and then use Multiuserchar
To send the message. Network Send, note Create a new worker thread: '
Message message = new Message ();                    Settings sent to who                    Message.setto ("[email protected]");                    Message.setfrom ("[email protected]");                    Message.settype (Message.Type.groupchat);                    LOG.I ("Asmack", Message.getfrom ());                    Sets the content of the message                    message.setbody (body);                    To send a                    MyService.multiUserChat.sendMessage (message);

  
Here's why I sent a message to the room why the room will be sent to me, here to explain because you are in the room will automatically receive the message, that is, the room will automatically push the message to you. If it's a single-chat mode, there's no such repetitive push. For example, the following message accepts a server:
                        /** * Receive messages here * */Xmppconn                            Ection.addpacketlistener (New Packetlistener () {///If the server sends a message to the client, perform the following method @Override public void Processpacket (Packet Packet) {if (pack ET instanceof message) {//cast judgment type final Message me                                    Ssage = (Message) packet;                                    Message.type Type = Message.gettype ();                                    Final Messagemodel Messagemodel = new Messagemodel ();  if (type = = Message.Type.groupchat) {/** *                                        The worker thread is not able to move the UI * * */ if (charactivity.instance ! = null) {CharActivity.instance.runOnUiThread (new Runnable () {                                                    @Override public void Run () { This goes to the main thread Messagemodel.setfrom                                                    (Message.getfrom ());                                                    Messagemodel.setmessage (Message.getbody ());                                                    Here to test log.i ("Server", Message.getfrom ()); if (charactivity.instance! = null) {Charact                                                        Ivity.instance.data.add (Messagemodel);                                                    Handler.sendemptymessage (0); }                                                }                                            });                        }                                    }                                }                            } }, NULL);

The following method is called when a new message is received in the room:
Note that there is no UI in the worker thread, so use this method to change the UI of the chat interface, which is used for singleton mode
CharActivity.instance.runOnUiThread (New Runnable ()
Another point is that the data of the ListView cannot be updated in the thread, so it is solved with handler+message
Private Handler Handler = new Handler () {        @Override public        void Handlemessage (Android.os.Message msg) {            Super.handlemessage (msg);            Switch (msg.what) {case                0:                    CharActivity.instance.messageAdapter.notifyDataSetChanged ();//                    CharActivity.instance.lvMessage.setAdapter (CharActivity.instance.messageAdapter);                    CharActivity.instance.lvMessage.setSelection (CharActivity.instance.data.size ());                    Break;}}    ;

Perform:
Handler.sendemptymessage (0);
   
About Asmack Frame Chat Simple introduction is so much, will be introduced in the cloud-based SDK for the third-party SDK of the implementation of instant messaging, here based on the Asmack framework is a general introduction to specific single-chat files to send these common features of the implementation can be completed later, such as single chat:
/** * Send Message *  * @param to * @param msg */public static void Sendtalkmsg (string to, String msg) {chat chat = Myapplicati On.xmppConnection.getChatManager (). Createchat (to, null); try {chat.sendmessage (msg); Connecmethod.postfiletoservice ("130560779417728750.png", text_loading);} catch (Xmppexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}

Finally, thank you for your support, don't forget to scan your avatar to follow the public number "passion Naked Chat" Thank you ~~~~~~!

Asmack-based Chat

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.