How do I keep the XMPP connection in the app?

I am currently working on an application that uses the asmack lib to connect to an XMPP server. This application mainly includes sending / receiving messages, changing statuses, etc.

Currently, the XMPP connection is inside the application and is not a kind of background service. So now I'm wondering if it's better to keep the network connected using a service, or just keep the realtime connection when my application is actually running.

This allows for the fact that I want to stay connected to the XMPP server all the time my app is running in the background and when the user returns to any activity that has an XMPP connection. I liked this when it comes to basic action (meaning I am connecting to credentials) reconnecting the XMPP connection with the same credentials. but I ran into the problem that when I stay for some time in the contact view, the connection becomes closed after a while if this activity resumes, reverting to a fail on connection (like a null pointer exception). It is not possible to reconnect the connection here.

So my question is, is it better to (re) connect / login as soon as my activity is brought to the foreground / started, or is it better to connect once inside the service and just keep that connection alive?

If creating a service is better how to create a snippet and how to create an XMPP connection and I have to login and log out using buttons. How to save these parameters in the service.

Thanks in advance,

+3


source to share


1 answer


If you want to keep connecting to your XMPP server Service

this is the way to go.

So, once the user is logged in, you can start the message Service

and continue, and when the user logs out, stopService

You can show notifications from your own Service

, which will open the action when clicked.



If you have a simple communication (like passing multiple commands) between your service and your activity, you can do it with LocalBroadcastManager

, but if your communication is more complex (like an activity listening for an event on a service), consider creating service binder

one that is used inactivity

This example skeleton of a service supporting bind

public class MyService extends Service {
    private final IBinder binder = new ServiceBinder();

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      onHandleIntent(intent);
      return START_STICKY;
   }

   protected void onHandleIntent(Intent intent) {
       // handle intents passed using startService()
   }

   @Override
   public IBinder onBind(Intent intent) {
    return binder;
   }

   public class ServiceBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }
}

      

+6


source







All Articles