Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep XMPP connection (using asmack) alive on Android

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?

like image 709
danilodeveloper Avatar asked Oct 05 '11 13:10

danilodeveloper


1 Answers

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.

like image 154
Flow Avatar answered Sep 19 '22 13:09

Flow