Keep XMPP connection (using asmack) alive on Android

怎甘沉沦 提交于 2019-12-18 10:45:04

问题


I'm developing an application that receives push notifications via XMPP ( I know C2DM, but it has some limitations and I can't use because of it ), the problem is the connection that after some time is garbage collected and I can't send push notification to the Android device.

I think I need to implement an Android service but I have no idea how to implement a service that would keep the connection alive. Somebody could help me?


回答1:


I am not sure if "garbage collected" is the right term here. It is more likely that your activity simply gets closed by Android, because you create the connection in an Activity.

But you are right, in order to keep a stable connection you need to put the XMPP connection into a Service. But make sure that the connection is in an extra thread, because a service for itself is not a extra process or thread. This could be done, for example with an Handler.

HandlerThread thread = new HandlerThread(SERVICE_THREAD_NAME);
thread.start();
handlerThreadId = thread.getId();
serviceLooper = thread.getLooper();
serviceHandler = new ServiceHandler(serviceLooper);

Then you can communicate with the Service Thread via messages/intents. Another alternative would be a Binder interface.

You could also have a look on how others do this: Beem and GTalkSMS are both open source projects that implement an XMPP connection with an Android service. GTalkSMS uses the IntentService approach, whereas Beem uses an Binder to communicate with the XmppConnection.

Note that we achive a pretty stable connection with GTalkSMS, but it's never so good as the stock GTalk Service/Client. One reason is that smacks default keep-alive check timer is 5 minutes, which is way to often for a mobile device when you want to save as much battery as possible. So I had to set it to a higher value, which comes with some drawbacks. You will always have a trade-off between a fast, responsive and stable connection vs. battery life when it comes to this.



来源:https://stackoverflow.com/questions/7661909/keep-xmpp-connection-using-asmack-alive-on-android

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