how to handle keep alive connection in android Service

情到浓时终转凉″ 提交于 2020-01-14 09:00:10

问题


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.



来源:https://stackoverflow.com/questions/11973850/how-to-handle-keep-alive-connection-in-android-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!