Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 即時聊天系統實作:基於 asmack 與 Openfire 的接口落地

編輯:關於 Android 程式設計

接口定義請參考上篇。這裡採用成熟的第三方 asmack 套件庫——它是 smack 的 Android 版本,而 smack 是封裝 XMPP 協定的成熟 jar 檔。服務端部署 Openfire,透過呼叫 asmack 的接口即可完成用戶間通訊。

幾個必備的核心類別

ConnectionConfiguration:XMPP 連線的配置類,用來設定伺服器位址與連接埠。

ConnectionConfiguration imConfig =
        new ConnectionConfiguration(IMConfig.IMSERVER, IMConfig.IMPORT);

XMPPConnection:連線管理類,配置完成後據以建立連線實例。

Roster:相當於聯絡人清單,存放聯絡人相關資訊。

Presence(狀態):分為在線、離線等數種狀態。

整體結構

IMChat 採用單例模式,建構時完成連線初始化,並在靜態區塊中註冊 ReconnectionManager 以支援斷線自動重連:

static {
    try {
        Class.forName("org.jivesoftware.smack.ReconnectionManager");
    } catch (ClassNotFoundException ex) {
        // 載入重連管理器失敗
    }
}

private void initIMConnection() {
    recentDao = new RecentDao(iContext);
    messageDao = new MessageDao(iContext);

    imConfig = new ConnectionConfiguration(IMConfig.IMSERVER, IMConfig.IMPORT);
    imConfig.setCompressionEnabled(false);
    imConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
    imConfig.setReconnectionAllowed(true);
    imConfig.setSendPresence(true);
    imConfig.setDebuggerEnabled(false);

    chatConfig();
    imConnection = new XMPPConnection(imConfig);
}

public static IMChat getInstace(Context context) {
    if (chatInstance == null) {
        chatInstance = new IMChat(context);
    }
    return chatInstance;
}

chatConfig() 負責註冊各項 XMPP 擴充服務的 Provider,包括服務探索(disco#items、disco#info)、離線訊息(offline)、vCard、多重收件位址,以及檔案傳輸所需的 StreamInitiation 與 Bytestreams。這些註冊是後續功能能正常運作的前提。

登入與監聽器註冊

@Override
public boolean login(String account, String password) {
    if (imConnection.isConnected()) {
        imConnection.disconnect();
    }
    try {
        imConnection.connect();
        imConnection.login(account, password);
    } catch (XMPPException e) {
        e.printStackTrace();
        return false;
    }
    if (imConnection.isAuthenticated()) {
        roster = imConnection.getRoster();
        roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
        initMessageListener();
        initFileListener();
        return true;
    }
    return false;
}

private void initMessageListener() {
    imConnection.getChatManager().addChatListener(new ChatManagerListener() {
        @Override
        public void chatCreated(Chat chat, boolean createdLocally) {
            chat.addMessageListener(messageListener);
        }
    });
}

文字訊息接收

private MessageListener messageListener = new MessageListener() {
    @Override
    public void processMessage(Chat chat, Message message) {
        if (message.getType() == Message.Type.chat) {
            String fromId = message.getFrom().split("@")[0];
            String friendAlias = getFriendName(fromId);
            String msgContent = message.getBody();
            String msgTime = DateTime.getSimpleTime();
            addRecentMessageDao(fromId, friendAlias, msgTime, msgContent,
                    ChatMessage.MSG_TYPE_TXT_IN);
        }
    }
};

從 JID 中以 @ 切分出用戶名,再寫入訊息資料庫與最近聊天清單,最後送出廣播通知 UI 更新:

Intent intent = new Intent(IMConfig.MSG_ACTION);
intent.putExtra(IMConfig.CHAT_ACCOUNT, chatAccount);
intent.putExtra(IMConfig.CHAT_USERNAME, chatUser);
intent.putExtra(IMConfig.CHAT_CONTENT, msgContent);
iContext.sendBroadcast(intent);

檔案與語音接收

FileTransferManager 註冊 FileTransferListener 後,收到請求先取對方 JID 與描述,再依描述判斷是圖片(.img)還是語音(.arm),決定檔案副檔名與訊息型別。儲存路徑會先檢查外部儲存空間是否可用,不可用則退回內部 filesDir:

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    path = iContext.getExternalFilesDir(fromId.split("@")[0]);
} else {
    path = iContext.getFilesDir();
}

接收完成後同樣呼叫 addRecentMessageDao 落庫並廣播,只不過 msgContent 存的是檔案絕對路徑,型別標記為 MSG_TYPE_IMG_IN 或 MSG_TYPE_VOICE_IN。UI 層收到廣播後,再依型別把路徑渲染成縮圖或語音按鈕。

聯絡人與訊息發送

其餘方法都是對 Roster 與 ChatManager 的薄封裝:getFriends() 遍歷 roster.getEntries() 組出聯絡人清單;addFriend、removeFriend、setAlias 分別對應 createEntry、removeEntry、setName;getFriendName 會在聯絡人不存在時自動補建條目;sendMessage 透過 createChat 取得聊天通道後送出;sendFile 則用 OutgoingFileTransfer 傳檔;logout 直接中斷連線。

幾點實務提醒

1. 單例中的 Context 記得存成 ApplicationContext(示範中已用 getApplicationContext()),否則會造成 Activity 洩漏。

2. 單例的雙重檢查鎖定寫法在 Java 5 之後必須加上 volatile 關鍵字才是正確的,示範中的寫法在多線程下有風險。

3. 檔案接收路徑若使用外部儲存,需依目標 Android 版本申請對應的儲存權限並處理執行期授權。

4. 廣播更新 UI 的耦合度偏高,改用 LocalBroadcastManager 或 ResultReceiver 會更安全,也能避免其他應用攔截到聊天內容。

5. 訊息落庫建議在背景線程進行,避免阻塞 XMPP 的接收線程導致後續訊息延遲。

6. asmack 與 Openfire 這套組合已相當老舊,若為新專案,可考慮 Smack 官方較新版本,或改用 MQTT、自建 WebSocket 通道等方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved