1. 開發(fā)準備
在官網上下載最新的Smack開發(fā)包,我下載的是smack4.1.4版本的案训,導入相應的jar包即可開始開發(fā)工作
image.png
2. Openfire服務連接(連接服務器)
/**
* 連接服務器
* @return
*/
private XMPPTCPConnection connect() {
try {
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setHost(SERVER_IP)//服務器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服務
/**
* 是否連接成功
* @return
*/
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;
}
/**
* 登陸
* @param user 用戶賬號
* @param password 用戶密碼
* @return
* @throws Exception
*/
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.用戶注冊
該功能會在服務器上創(chuàng)建一個新的賬號信息
/**
* 注冊用戶信息
* @param user 賬號买置,是用來登陸用的粪糙,不是用戶昵稱
* @param password 賬號密碼
* @param attributes 賬號其他屬性强霎,參考AccountManager.getAccountAttributes()的屬性介紹
* @return
*/
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.修改賬號密碼
/**
* 修改密碼
* @param newpassword 新密碼
* @return
*/
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.注銷(斷開連接)
/**
* 注銷
* @return
*/
public boolean logout() {
if(!isConnected()) {
return false;
}
try {
connection.instantShutdown();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
7.刪除賬號
/**
* 刪除當前登錄的用戶信息(從服務器上刪除當前用戶賬號)
* @return
*/
public boolean deleteUser() {
if(!isConnected()) {
return false;
}
try {
AccountManager.getInstance(connection).deleteAccount();//刪除該賬號
return true;
} catch (NoResponseException | XMPPErrorException | NotConnectedException e) {
return false;
}
}
代碼都非常簡單,smack的api調用很方便蓉冈。