how to handle keep alive connection in android Ser

2019-06-19 18:17发布

问题:

I am using asmack for an android IM application, where I am using remote service with AIDL interface.

Inside of onStartCommand method of my service I write code as below. I create connection and then login using that. When anyone run my application inside onCreate method of main activity of my application run my service getApplicationContext.StartService(serviceIntent). It's working fine, but after few minutes (sometimes 10 minutes and some time more than ten) messageListener that I attach inside of service stops to receive messages. But I know that the connection exist, because same time I use xmppConnection to send message it's sending message to user B but it not listening messages from user B. I don't know why my listener stop hearing message.

public int onStartCommand(final Intent intent, final int flags, final int startId) {
    ConnectionConfiguration config = new ConnectionConfiguration(URL, MyPort, Host);
    xmppConnection = new XMPPConnection(config);
    xmppConnection.connect();
    xmppConnection.login("someid@sample.com", "testpass");
    xmppConnection.addPacketListener(myMessageListener, new PacketTypeFilter(Message.class));
    return START_STICKY;
}
private PacketListener myMessageListener = new PacketListener() {
    public void processPacket(Packet packet) {
        Message msg = (Message) packet;
    }
}

Please guide.

回答1:

Is your connection being closed on error without you noticing ? You should add a connection listener and a log for each callback to debug the connection state.

On Android it's possible to have a "zombie" socket: you can still write to it, but the recipient will never receive the messages, and of course you won't be able to read new messages from it. It can happen after a network status change.

To detect that I use XMPP Ping, initiated from the client from an alarm (every 15 minutes with inexact repeating). And I disable white space keep alive. This defeats most of the timeout mechanisms that can exist between your client and your server (NAT or proxies). Plus, if you don't receive any answer to the ping (within 20s for example), you can assume the connection is in a bad state and reconnect manually.