我使用服务来保持我的xmpp连接始终处于活动状态,这是代码:
public class XMPPService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new ConnectionStatus().execute();
return START_STICKY;
}
@Override
public void onCreate() {
Log.i("service", "created");
}
public class ConnectionStatus extends AsyncTask{
@Override
protected Object doInBackground(Object[] params) {
XMPPClient.getConnection().addConnectionListener(
new AbstractConnectionListener() {
public void connectionClosed() {
Log.i("connection", "closed");
}
public void connectionClosedOnError(Exception e) {
Log.i("connection", "closed on error");
}
public void reconnectionFailed(Exception e) {
Log.i("reconnection", "failed");
}
public void reconnectionSuccessful() {
if (XMPPClient.getConnection().isAuthenticated()) {
Log.i("isauthenticauted : ", String.valueOf(XMPPClient.getConnection().isAuthenticated()));
Log.i("reconnection", "succesful");
} else {
try {
XMPPClient.getConnection().login(new TinyDB(getApplicationContext()).getString("username"), new TinyDB(getApplicationContext()).getString("password"));
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("reconnection", "succesful");
}
}
public void reconnectingIn(int seconds) {
Log.i("reconnectingIn", String.valueOf(seconds));
}
}
);
return null;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
但连接会定期断开连接,我明白了:
org.jivesoftware.smack.SmackException: Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1148)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
at java.lang.Thread.run(Thread.java:818)
然后它开始重新连接到服务器,然后我得到了这个:
09-07 17:56:03.916 17754-20996/com.sports.unity D/SMACK﹕ SENT (0): `09-07 17:56:04.217 17754-20997/com.sports.unity D/SMACK﹕ RECV (0): <?xml version='1.0'?><stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='2025993121' from='mm.io' version='1.0' xml:lang='en'><stream:features><c xmlns='http://jabber.org/protocol/caps' hash='sha-1' node='http://www.process-one.net/en/ejabberd/' ver='Kyn00yB1iXiJLUJ0gVvn7tZREMg='/><register xmlns='http://jabber`
如何与xmpp服务器保持稳定的连接