Android smack4.2的简单使用
1.使用背景
在搭建即时通讯的时候,一般采用Openfire+smack实现(如:第三方环信 )。由于Asmack已经废弃。所以先使用官方最新库 : GitHub上的指导
2.使用大致流程
2.1新建一个工程,导入以下依赖
repositories {
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots'
}
mavenCentral()
}
dependencies {
compile "org.igniterealtime.smack:smack-android-extensions:4.2.0"
compile "org.igniterealtime.smack:smack-tcp:4.2.0"
compile "org.igniterealtime.smack:smack-android:4.2.0"
}
2.2连接Openfire服务器
InetAddress address = InetAddress.getByName(Const.ip);
//配置信息
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setXmppDomain("192.168.100.116")//设置xmpp域名
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)//安全模式认证
.setHostAddress(address)
.setPort(Const.port)
.build();
xmpptcpConnection = new XMPPTCPConnection(config);//连接类
xmpptcpConnection.connect();
2.3 .用户登录
//设置是否在线状态,和状态说明
Presence presence = new Presence(Presence.Type.unavailable);
presence.setStatus("Gone fishing");
xmpptcpConnection.sendStanza(presence);
xmpptcpConnection.login(userName, password);//关键代码
2.4用户好友获取
两种方式:(1)
Roster instanceFor = Roster.getInstanceFor(xmpptcpConnection);
Set entries = instanceFor.getEntries();
for (RosterEntry entry:entries) {
entry.getType();
entry.getName();//昵称
entry.getGroups();//好友所在的组
entry.getJid().getDomain();//好友域名
entry.getJid().getLocalpartOrNull();//好友名称
entry.getUser();//(废弃)好友完整名称(包括域名)
}
(2)
Roster instanceFor = Roster.getInstanceFor(xmpptcpConnection);
Collection groups = instanceFor.getGroups();
group.getName();//获取用户组名
for (RosterGroup group:groups) {
List entries = group.getEntries();
for (RosterEntry entry : entries) {
}
}
2.5接收消息和发送消息
(1) 接收消息:获取聊天管理器,注册获取消息监听
ChatManager chatManager = ChatManager.getInstanceFor(xmpptcpConnection);
chatManager.addIncomingListener(new IncomingChatMessageListener() {
@Override
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
if (message.getBody() != null) {
Log.e("消息接收——", message.getBody().toString() + "");
}
}
});
(2)发送消息:获取聊天管理器,指定消息接收人,发送消息
ChatManager chatManager = ChatManager.getInstanceFor(xmpptcpConnection);
//JidCreate.entityBareFrom("用户名@域名");获取用户ID
EntityBareJid jid = JidCreate.entityBareFrom("xxx@192.168.100.116");
Chat chat = chatManager.chatWith(jid);
chat.send("woaini1");
//Add a new listener for outgoing chat messages.
chatManager.addOutgoingListener(new OutgoingChatMessageListener() {
@Override
public void newOutgoingMessage(EntityBareJid to, Message message, Chat chat) {
Log.e("发哦送消息", "" + message.getBody().toString());
}
});
至于其他的相关操作可能留待以后吧。。。。第一次在简书上写文章,如若有不当之处,请指教