1. 开发准备
在官网上下载最新的Smack开发包,我下载的是smack4.1.4版本的,导入相应的jar包即可开始开发工作
2. Openfire服务连接(连接服务器)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
private XMPPTCPConnection connect() { try { XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder() .setHost(SERVER_IP) .setPort(PORT) .setServiceName(SERVER_NAME) .setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled) .setCompressionEnabled(false) .setDebuggerEnabled(true).build(); XMPPTCPConnection connection = new XMPPTCPConnection(config); connection.connect(); return connection; } catch (Exception e) { return null; } }
|
3.登陆Openfire服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
private boolean isConnected() { if(connection == null) { return false; } if(!connection.isConnected()) { try { connection.connect(); return true; } catch (SmackException | IOException | XMPPException e) { return false; } } return true; }
public boolean login(String user, String password) throws Exception { if(!isConnected()) { return false; } try { connection.login(user, password); return true; } catch (Exception e) { throw e; } } ```
### 4.用户注册
该功能会在服务器上创建一个新的账号信息 ```java
public boolean registerUser(String user, String password, Map<String, String> attributes) { if(!isConnected()) { return false; } try { AccountManager.getInstance(connection).createAccount(user, password, attributes); return true; } catch (NoResponseException | XMPPErrorException | NotConnectedException e) { Log.e(TAG, "注册失败", e); return false; } }
|
5.修改账号密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
public boolean changePassword(String newpassword) { if(!isConnected()) { return false; } try { AccountManager.getInstance(connection).changePassword(newpassword); return true; } catch (NoResponseException | XMPPErrorException | NotConnectedException e) { Log.e(TAG, "密码修改失败", e); return false; } }
|
6.注销(断开连接)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
public boolean logout() { if(!isConnected()) { return false; } try { connection.instantShutdown(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
|
7.删除账号
public boolean deleteUser() {
if(!isConnected()) {
return false;
}
try {
AccountManager.getInstance(connection).deleteAccount();
return true;
} catch (NoResponseException | XMPPErrorException | NotConnectedException e) {
return false;
}
}
代码都非常简单,smack的api调用很方便。
write by laohu
2015-10-30
原创文章,转载请出处注明。
下面是我的个人公众号,欢迎关注交流