Smack Client Configuration for Instant Messaging

Source: Internet
Author: User
Tags gettext

Prior to learning through Openfire+spark+smack mode to complete our instant Messenger software, the last time we have completed the installation and configuration of OpenFire, this time we continue to complete our client section.

1. First we use Baidu smack to download the jar package we need, import the downloaded jar package into our project, create a tool class Xmpptool:

Package Com.xmpp.client.util;import Org.jivesoftware.smack.connectionconfiguration;import Org.jivesoftware.smack.xmppconnection;import Org.jivesoftware.smack.xmppexception;import Org.json.JSONArray;    public class Xmpptool {private static xmppconnection con = null;             private static void OpenConnection (string url, string pcname) {try {//URL, port, can also be set to connect server name, address, port, user. Connectionconfiguration connconfig = new Connectionconfiguration ("192.168.2.113", 5222, "J            Erehedu ");            con = new Xmppconnection (connconfig);        Con.connect ();        } catch (Xmppexception Xe) {xe.printstacktrace (); }} private static void Openoffconnection (string url, string pcname) {try {Connectionconfigurati            On connconfig = new Connectionconfiguration (URL, 5222, pcname);            Connconfig.setsendpresence (FALSE);            con = new Xmppconnection (connconfig); Con.connect ();        } catch (Xmppexception Xe) {xe.printstacktrace ();            }} public static xmppconnection getoffconnection (string url, string pcname) {if (con = = null) {        Openoffconnection (URL, pcname);    } return con; public static xmppconnection getconnection (string url, string pcname) {if (con = = null) {Openconn        Ection (URL, pcname);    } return con;        } public static void CloseConnection () {con.disconnect ();    con = null; }}
Tool Class Xmpptool

Mainly through the connectionconfiguration to connect to the server, passing in three parameters (address, port, user name)

2. Login interface

Package Com.xmpp.client;import Java.util.iterator;import Org.jivesoftware.smack.xmppexception;import Org.jivesoftware.smack.packet.presence;import Org.jivesoftware.smackx.offlinemessagemanager;import Com.xmpp.client.util.xmpptool;import Com.xmpp.client.r;import Android.app.activity;import android.content.Intent; Import Android.os.bundle;import android.os.handler;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.linearlayout;import Android.widget.toast;public class Formlogin extends Activity implements    Onclicklistener {private EditText useridtext, Pwdtext, Urltext, pcnametext;;    Private LinearLayout layout1, Layout2;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.formlogin);       Get user and password This.useridtext = (EditText) Findviewbyid (R.id.formlogin_userid); This.pwdtext = (EditText) Findviewbyid (R.ID.FORMLOGIN_PWD);        This.urltext = (EditText) Findviewbyid (R.id.formlogin_url);        This.pcnametext = (EditText) Findviewbyid (r.id.formlogin_pcname);        Logging in THIS.LAYOUT1 = (linearlayout) Findviewbyid (R.ID.FORMLOGIN_LAYOUT1);        Login interface This.layout2 = (linearlayout) Findviewbyid (R.ID.FORMLOGIN_LAYOUT2);        Button Btsave = (button) Findviewbyid (R.id.formlogin_btsubmit);        Btsave.setonclicklistener (this);        Button Btcancel = (button) Findviewbyid (R.id.formlogin_btcancel);    Btcancel.setonclicklistener (this); } @Override public void OnClick (View v) {/////by ID to commit or cancel switch (V.getid ()) {case R.ID.FORML Ogin_btsubmit://Get filled in user and password//get filled in user and password final String USERID = This.useridText.getText (            ). ToString ();            Final String PWD = This.pwdText.getText (). toString ();   Final String URL = This.urlText.getText (). toString ();         Final String pcname = This.pcnameText.getText (). toString ();                    Thread t = new Thread (new Runnable () {public void run () {//Sendemptymessage: Send a message                    Handler.sendemptymessage (1);                                try {//Connect xmpptool.getoffconnection (URL, pcname). Login (USERID,                        PWD);                        Getofflinemessage ();                        state presence Presence = new presence (Presence.Type.available);                        Xmpptool.getconnection (URL, Pcname). Sendpacket (presence);                        Intent Intent = new Intent ();                        Intent.setclass (Formlogin.this, Formclient.class);                        Intent.putextra ("userid", UserID);                        Intent.putextra ("url", url); Intent.putextra ("Pcname", Pcname);                        FormLogin.this.startActivity (Intent);                    FormLogin.this.finish ();                        } catch (Xmppexception e) {xmpptool.closeconnection ();                    Handler.sendemptymessage (2);            }                }            });            T.start ();        Break            Case R.id.formlogin_btcancel:finish ();        Break }}/** * Get offline message */private void Getofflinemessage () {Offlinemessagemanager Offlinemanager = new Offlinemessagemanager (Xmpptool.getconnection (This.urlText.getText (). toString (), Thi        S.pcnametext.gettext (). toString ());        Iterator<org.jivesoftware.smack.packet.message> it;            try {it = offlinemanager.getmessages ();                while (It.hasnext ()) {Org.jivesoftware.smack.packet.Message Message = It.next (); LOG.I ("Offline message", "Received offline message, ReceIved from "" + message.getfrom () + "" "Message:" + message.getbody ());        }//delete offline message offlinemanager.deletemessages ();        } catch (Xmppexception e) {//TODO auto-generated catch block E.printstacktrace ();            }} private Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {                if (msg.what = = 1) {layout1.setvisibility (view.visible);            Layout2.setvisibility (View.gone);                } else if (msg.what = = 2) {layout1.setvisibility (view.gone);                Layout2.setvisibility (view.visible); Toast.maketext (formlogin.this, "Login failed!            ", Toast.length_short). Show ();    }        }; };}
Login Interface

3. Chat Client

Package Com.xmpp.client;import Java.io.file;import Java.util.arraylist;import java.util.date;import Java.util.iterator;import Java.util.list;import Org.jivesoftware.smack.chat;import Org.jivesoftware.smack.chatmanager;import Org.jivesoftware.smack.chatmanagerlistener;import Org.jivesoftware.smack.messagelistener;import Org.jivesoftware.smack.packetlistener;import Org.jivesoftware.smack.xmppexception;import Org.jivesoftware.smack.packet.message;import Org.jivesoftware.smack.packet.packet;import Org.jivesoftware.smackx.filetransfer.filetransfer;import Org.jivesoftware.smackx.filetransfer.filetransfer.status;import Org.jivesoftware.smackx.filetransfer.filetransferlistener;import Org.jivesoftware.smackx.filetransfer.filetransfermanager;import Org.jivesoftware.smackx.filetransfer.filetransferrequest;import Org.jivesoftware.smackx.filetransfer.incomingfiletransfer;import Org.jivesoftware.smackx.filetransfer.outgoingfiletransfer;import Org.jivesoftware.smackx.muc.MultiUserChat; Import org.jiveSoftware.smackx.packet.delayinformation;import Android.app.activity;import Android.app.alertdialog;import Android.content.context;import Android.content.dialoginterface;import Android.content.intent;import Android.os.bundle;import Android.os.handler;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.button;import Android.widget.edittext;import Android.widget.listview;import Android.widget.progressbar;import Android.widget.textview;import Android.widget.toast;import Com.lidroid.xutils.httputils;import com.lidroid.xutils.exception.HttpException; Import Com.lidroid.xutils.http.requestparams;import Com.lidroid.xutils.http.responseinfo;import Com.lidroid.xutils.http.callback.requestcallback;import Com.lidroid.xutils.http.client.HttpRequest.HttpMethod; Import Com.xmpp.client.util.screenshot;import Com.xmpp.client.util.timerender;importCom.xmpp.client.util.xmpptool;public class Formclient extends Activity {private Myadapter adapter;    Private list<msg> listmsg = new arraylist<msg> ();    Private String Puserid;    Private EditText Msgtext, Totext;    Private ProgressBar PB;        Private Button btsend;        Private TextView WAITPB;    Private String URL;    Private String Pcname;    private String person;    Private Chat Mychat;        Private Chatmanager cm;        public class MSG {String userid;        String msg;        String date;        String from;            Public MSG (String userid, String Msg, String date, string from) {This.userid = userid;            this.msg = msg;            This.date = date;        This.from = from;        }} @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.formclient); Gets the user name passed intent, Url,pcname This.puserid = Getintent (). Getstringextra ("USerid "); This.        url = getintent (). Getstringextra ("url"); This.        Pcname = Getintent (). Getstringextra ("Pcname");        ListView ListView = (ListView) Findviewbyid (R.id.formclient_listview);        Listview.settranscriptmode (Listview.transcript_mode_always_scroll);        This.adapter = new Myadapter (this);        Listview.setadapter (adapter);        Get text Information This.msgtext = (EditText) Findviewbyid (R.id.formclient_text);                Get Chat Object this.totext = (EditText) Findviewbyid (r.id.formclient_to);        Send a message to the WATER-PC server water (get your own server, and friends)//message listener cm = Xmpptool.getconnection (URL, Pcname). Getchatmanager ();        Chatlistener ();        Send Message Btsend = (Button) Findviewbyid (r.id.formclient_btsend);            Sendchatmessage (); }/** * Send Chat message * */private void Sendchatmessage () {Btsend.setonclicklistener (NE W Onclicklistener () {@Override public void OnClick (View v){//Get text text String msg = Msgtext.gettext (). toString ();                person = Totext.gettext (). toString ();                Mychat = cm.createchat (person + "@" + pcname, NULL); if (msg.length () > 0) {//Send message Listmsg.add (new msg (Puserid, MSG, timerender.getd                    Ate (), "out"));                    Refresh Adapter adapter.notifydatasetchanged ();                    try {//Send a message to the specified person Mychat.sendmessage (msg);                    } catch (Xmppexception e) {e.printstacktrace ();                            }} else {Toast.maketext (formclient.this, "Please enter information", Toast.length_short)                . Show ();            }//Empty text Msgtext.settext ("");    }        });       }/** * Listener single message */private void Chatlistener () { Cm.addchatlistener (New Chatmanagerlistener () {@Override public void chatcreated (chat chat, Boolean Able) {Chat.addmessagelistener (new MessageListener () {@Override PU Blic void ProcessMessage (Chat chat2, message message) {LOG.V ("--tags--", "--tags-form--" + Message                        . Getfrom ());                        LOG.V ("--tags--", "--tags-message--" + message.getbody ());                            Receive messages from WATER-PC server water (get your own server, and friends) if (Message.getfrom (). Contains (Puserid + "@keyi-pc")) {                                    Get user, message, time, in string[] args = new string[] {Puserid,                           Message.getbody (), Timerender.getdate (), "in"};                            Android.os.Message msg = Handler.obtainmessage ();                   Msg.what = 1;         Msg.obj = args;                        Msg.sendtotarget (); } else {} log.i ("JSON"                            , "B" + message.getbody ());                            String amsg = Message.getbody ();                                                        string[] args = null;                                args = new string[] {message.getfrom (), Amsg, Timerender.getdate (), "in"};                                Android.os.Message msg = handler. Obtainmessage ();                                Msg.what = 1;                                Msg.obj = args;                                                Msg.sendtotarget ();            }                                     });    }        });    } private Outgoingfiletransfer Filetransfer;   Handler Outhandler = new Handler (); Runnable outrunnable = new Runnable () {@Override public void run () {if (Filetransfer.getprogre                SS () = = 1) {pb.setvisibility (view.gone);            Outhandler.removecallbacks (outrunnable);        } outhandler.postdelayed (outrunnable, 100);        }    }; Private Handler Handler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (ms                G.what) {Case 1://Get message and show string[] args = (string[]) msg.obj;                Listmsg.add (New MSG (Args[0], args[1], args[2], args[3]));                Refresh Adapter adapter.notifydatasetchanged ();            Break Case 2://Attachment progress bar if (pb.getvisibility () = = View.gone) {pb.setvisibility (                    view.visible);                Waitpb.setvisibility (view.visible);            } break; Case 3:PB.SETPRogress (MSG.ARG1);            Break                Case 4:pb.setvisibility (View.gone);                Waitpb.setvisibility (View.gone);                                        Break            Default:break;    }        };    };        Exit @Override public void onbackpressed () {super.onbackpressed ();        Xmpptool.closeconnection ();        System.exit (0);    Android.os.Process.killProcess (Android.os.Process.myPid ());        } class Myadapter extends Baseadapter {private Context cxt;        Private Layoutinflater Inflater;        Public Myadapter (Formclient formclient) {this.cxt = formclient;        } @Override public int getcount () {return listmsg.size ();        } @Override public Object getItem (int position) {return listmsg.get (position);        } @Override public long getitemid (int position) {return position;      }  @Override public View getView (int position, View Convertview, ViewGroup parent) {//Display the layout of the message: content, background, user, Time This.inflater = (layoutinflater) this.cxt. Getsystemservice (Context.layout_inflater_servi            CE);                         In,out Picture if (listmsg.get (position). From.equals ("in")) {Convertview = This.inflater.inflate (            R.layout.formclient_chat_in, NULL);            } else {Convertview = this.inflater.inflate (r.layout.formclient_chat_out, NULL); } TextView Useridview = (TextView) convertview. Findviewbyid (R.id.formclient_row_u            Serid);            TextView Dateview = (TextView) convertview. Findviewbyid (r.id.formclient_row_date);            TextView Msgview = (TextView) convertview. Findviewbyid (r.id.formclient_row_msg);         Useridview.settext (Listmsg.get (position). userid);   Dateview.settext (Listmsg.get (position). date);            Msgview.settext (Listmsg.get (position). msg);        return convertview; }    }}
Chat Client

There are a lot of classes that come with our own, and we just have to implement it.

Smack Client Configuration for Instant Messaging

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.