Android端使用asmack實現IM
阿新 • • 發佈:2019-02-06
昨天簡單介紹了一下 ejabberd 在Windows下的安裝,然後PC端來使用 spark 連線 ejabberd,今天一搗鼓了一下asmack
下面一步一步來
1.連線伺服器
//三個引數分別為:主機IP,埠(一般都是5222),安裝ejabberd時填寫的的域名 ConnectionConfiguration connectionConfig = new ConnectionConfiguration("192.168.1.100", 5222, "localhost"); // 允許自動連線 connectionConfig.setReconnectionAllowed(true); // 允許登陸成功後更新線上狀態 connectionConfig.setSendPresence(true); //下面為解決 找不到金鑰憑證,4.0+系統不同 Log.i("當前作業系統版本API Level=", Build.VERSION.SDK_INT + ""); //$NON-NLS-1$ //$NON-NLS-2$ if (Build.VERSION.SDK_INT >= 14) { connectionConfig.setTruststoreType("AndroidCAStore"); //$NON-NLS-1$ connectionConfig.setTruststorePassword(null); connectionConfig.setTruststorePath(null); } else { connectionConfig.setTruststoreType("BKS"); //$NON-NLS-1$ String path = System.getProperty("javax.net.ssl.trustStore"); //$NON-NLS-1$ if (path == null) path = System.getProperty("java.home") + File.separator //$NON-NLS-1$ + "etc" + File.separator + "security" //$NON-NLS-1$ //$NON-NLS-2$ + File.separator + "cacerts.bks"; //$NON-NLS-1$ connectionConfig.setTruststorePath(path); } connectionConfig.setSecurityMode(SecurityMode.disabled); //獲取到一個XMPPConnection物件 connection = new XMPPConnection(connectionConfig); try { connection.connect();// 開啟連線 } catch (XMPPException e) { throw new IllegalStateException(e); }
獲取賬戶管理類
accountManager = connection.getAccountManager();// 獲取賬戶管理類
註冊使用者
try {
accountManager.createAccount(username, password);
} catch (XMPPException e) {
e.printStackTrace();
}
登入
connection.login("使用者名稱", "密碼", "客戶端標識");
建立一個聊天
注意上面監聽訊息的寫法,smack 4.0.6的版本也是需要這樣寫,否則可能processMessage()不能被回撥ChatManager chatmanager = connection.getChatManager(); newChat = chatmanager.createChat(username + "@localhost", null); chatmanager.addChatListener(new ChatManagerListener() { @Override public void chatCreated(Chat arg0, boolean arg1) { arg0.addMessageListener(new MessageListener() { @Override public void processMessage(Chat chat, Message message) { Log.i("收到訊息", message.getFrom() + ":" + message.getBody()); } }); } });
傳送訊息
newChat.sendMessage(message);
修改狀態
//設定登陸後的個人狀態資訊
Presence p = new Presence(Presence.Type.available);
p.setStatus("吃飯...");
connection.sendPacket(p);
下線
connection.disconnect();
獲取好友列表
Collection<RosterEntry> rosters = connection.getRoster().getEntries(); Log.i("zyh","-------我的好友列表-------"); for(RosterEntry rosterEntry : rosters){ Log.i("zyh","name: "+rosterEntry.getName()+",jid: "+rosterEntry.getUser()); }