Android基於XMPP的即時通訊

來源:互聯網
上載者:User

標籤:

閑暇之餘,自己寫了個簡單的即時通訊,基於OpenFire伺服器平台。

整個項目包括兩個部分,一個是伺服器端,一個是android手機端;

 

一、關於伺服器端沒什麼好說的,下載安裝配置即可

推薦下載帶jar的程式安裝,配置好java_jdk的可以使用壓縮包解壓安裝

OpenFire:http://www.igniterealtime.org/downloads/index.jsp

順便下載一個Spark,電腦端通訊,用於和你的安卓手機互發資訊。

運行openFire

openfire的後台管理介面:

 

二、重點介紹一下android端的程式

1、首先要串連到OpenFire伺服器,需要一個登陸介面,像這樣

串連伺服器的代碼:

Thread thread = new Thread(new Runnable() {    public void run() {        try {            // 串連伺服器            XmppConnection.getConnection().login(userStr, passStr);            // 串連伺服器成功,更改線上狀態            Presence presence = new Presence(Presence.Type.available);            XmppConnection.getConnection().sendPacket(presence);            handler.sendEmptyMessage(1);        } catch (XMPPException e) {            XmppConnection.closeConnection();            handler.sendEmptyMessage(2);        }    }});thread.start();

XmppConnection類的核心代碼

public static int SERVER_PORT = 5222;//連接埠public static String SERVER_HOST = "192.168.1.169";//伺服器位址public static String SERVER_NAME = "pearlemon";//伺服器名稱private static XMPPConnection connection;private static void openConnection() {    try {        if (null == connection || !connection.isAuthenticated()) {            XMPPConnection.DEBUG_ENABLED = true;            ConnectionConfiguration conConfig = new ConnectionConfiguration(                    SERVER_HOST, SERVER_PORT, SERVER_NAME);            conConfig.setReconnectionAllowed(true);            conConfig.setSendPresence(true);            conConfig.setSASLAuthenticationEnabled(true);            connection = new XMPPConnection(conConfig);            connection.connect();            configureConnection();        }    } catch (XMPPException e) {    }}public static XMPPConnection getConnection() {    if (connection == null) {        openConnection();    }    return connection;}public static void closeConnection() {    connection.disconnect();    connection = null;}

2、串連到伺服器之後,擷取我們的好友,像這樣

擷取好友名單的代碼:

Thread thread = new Thread(new Runnable() {    public void run() {        try {            XMPPConnection conn = XmppConnection.getConnection();            Roster roster = conn.getRoster();            friendList = new ArrayList<Map<String,String>>();            Collection<RosterEntry> entries = roster.getEntries();            HashMap<String, String> map = null;            for (RosterEntry entry : entries) {                map = new HashMap<String, String>();                map.put("Name", entry.getName());                friendList.add(map);            }            handler.sendEmptyMessage(0);        } catch (Exception e) {            e.printStackTrace();        }    }});thread.start();

3、聊天介面的程式,像這樣

Spark聊天介面

接受訊息的代碼:

private ChatManager chatMan;private Chat newchat;
// 訊息監聽chatMan = XmppConnection.getConnection().getChatManager();newchat = chatMan.createChat(toUserID, null);chatMan.addChatListener(new ChatManagerListener() {    @Override    public void chatCreated(Chat chat, boolean able) {        chat.addMessageListener(new MessageListener() {            @Override            public void processMessage(Chat chat, Message message) {                // 收到來自pc伺服器的訊息(擷取自己好友發來的資訊)                if (message.getFrom().contains(toUserID)) {                    if (message.getBody().length() > 0) {                        // 擷取使用者、訊息、時間、IN                        String[] args = new String[] { toUserID,                                message.getBody() };                        // 在handler裡取出來顯示訊息                        android.os.Message msg = handler                                .obtainMessage();                        msg.what = 1;                        msg.obj = args;                        msg.sendToTarget();                    }                }            }        });    }});

發送訊息的代碼:

// 發送訊息String fromUserID = mAppGlobal.getName();String dateStr = DateTimeUtils.formatDate(new Date());chatList.add(new Msg(dateStr, fromUserID, content, "OUT"));// 重新整理適配器mAdapter.notifyDataSetChanged();mListView.setSelection(ListView.FOCUS_DOWN);//重新整理到底部 Thread thread = new Thread(new Runnable() {    @Override    public void run() {        try {            newchat = chatMan.createChat(toUserID + "@8nqa3d40s88hspl", null);            Message msg = new Message();            msg.setBody(content);            // 發送訊息            newchat.sendMessage(msg);        } catch (XMPPException e) {            e.printStackTrace();        }    }});thread.start();etSend.setText("");

基本就是這些東西了,源碼送上:http://files.cnblogs.com/files/pear-lemon/XmppTest.zip

Android基於XMPP的即時通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.