直接上代码,看注释应该很好理解,只是提供一种思路,不对的请大神指正:
public class PresenceService extends Service {标签:presence,cc,xmpp,Presence,离线,connection,Type,好友 From: https://blog.51cto.com/u_15955464/6058975
private _ConnectionControl cc = _ConnectionControl.getCC();//单例模式 保存了当前的链接
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("onDestroy", "PresenceService -- onDestroy");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Presence", "PresenceService-----" + (cc.connection == null));
if (cc.connection != null && cc.connection.isConnected()
&& cc.connection.isAuthenticated()) {//已经认证的情况下,才能正确收到Presence包(也就是登陆)
final String loginuser = cc.connection.getUser().substring(0,
cc.connection.getUser().lastIndexOf("@"));
//理解为条件过滤器 过滤出Presence包
PacketFilter filter = new AndFilter(new PacketTypeFilter(
Presence.class));
PacketListener listener = new PacketListener() {
@Override
public void processPacket(Packet packet) {
Log.i("Presence", "PresenceService------" + packet.toXML());
//看API可知道 Presence是Packet的子类
if (packet instanceof Presence) {
Log.i("Presence", packet.toXML());
Presence presence = (Presence) packet;
//Presence还有很多方法,可查看API
String from = presence.getFrom();//发送方
String to = presence.getTo();//接收方
//Presence.Type有7中状态
if (presence.getType().equals(Presence.Type.subscribe)) {//好友申请
} else if (presence.getType().equals(
Presence.Type.subscribed)) {//同意添加好友
} else if (presence.getType().equals(
Presence.Type.unsubscribe)) {//拒绝添加好友 和 删除好友
} else if (presence.getType().equals(
Presence.Type.unsubscribed)) {//这个我没用到
} else if (presence.getType().equals(
Presence.Type.unavailable)) {//好友下线 要更新好友列表,可以在这收到包后,发广播到指定页面 更新列表
} else {//好友上线
}
}
}
};
cc.connection.addPacketListener(listener, filter);
}
return super.onStartCommand(intent, flags, startId);
}
}