androidxmppchatsmackejabberd-saas

Best way to keepAlive Connection With Xmpp Server in Android


I am working on chat application and using ejabberd saas edition as xmpp server for it. I am using smack library ver-4.2.3. To keep connection alive I am using ping manager. Here is the code I am using:

ReconnectionManager.getInstanceFor(AppController.mXmpptcpConnection).enableAutomaticReconnection();
ServerPingWithAlarmManager.onCreate(context);
ServerPingWithAlarmManager.getInstanceFor(AppController.mXmpptcpConnection).setEnabled(true);
ReconnectionManager.setEnabledPerDefault(true);

//int i = 1;
// PingManager.setDefaultPingInterval(i);
PingManager.getInstanceFor(AppController.mXmpptcpConnection).setPingInterval(300);

I am using sticky-service also for connection, but when I keep my application open (ideal-state) for 15-20 mins then the connection is lost, so I am using ping manger to resolve this issue.

Is there any other better way of doing it or ping manager is the only option?


Solution

  • Best way to keep the alive connection with XMPP server you should reconnect after every network change.

    Like this:

    public class NetworkStateChangeReceiver extends BroadcastReceiver {
    
    private Context context;
    private static NetworkStateChangeListener mListener;
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
    this.context = context;
    try {
    if (!ApplicationHelper.isInternetOn(context)) {
    if (mListener != null) {
    mListener.OnInternetStateOff();
    }
    return;
    } else {
    XMPPTCPConnection xmpptcpConnection = XmppConnectionHelper.getConnection();
    if(!StringHelper.isNullOrEmpty(new SessionManager(context).getAuthenticationToken())) {
    Intent XmppConnectionServicesIntent = new Intent(context, XmppConnectionServices.class);
    context.stopService(XmppConnectionServicesIntent);
    context.startService(XmppConnectionServicesIntent);
    }
    }
    
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    
    //to initialize NetworkStateChangeListener because null pointer exception occurred
    public static void setNetworkStateChangeListener(NetworkStateChangeListener listener) {
    mListener = listener;
    }
    
    }