2
votes

I am implementing a chat app with XMPP protocol and Smack library.

I am making a connection to the server inside Service class. Everything works fine, sending and receiving messages, until some time passes and OS kills the app.

How I can keep my connection to the server alive all time?

1

1 Answers

0
votes

The best bet right now is to listen for connectivity changes using a BroadcastReceiver and connecting your XMPPTCPConnection if not already connected.

You can achieve it this way:

1) Register a broadcast receiver on ConnectivityManager.CONNECTIVITY_ACTION

2) Then implement onReceive():

@Override
public void onReceive(Context context, Intent intent) {
    if(!isInitialStickyBroadcast()) {
        Bundle extras = intent.getExtras();
        if(extras != null) {
            if(!extras.getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY)) {
                // call reconnection code!
            } 
        }
    }
}

Checkout this answer by smack developer. Although, this issue has been marked resolved in issue tracker but I was still facing problems using the ReconnectionManager.

Also, keeping the connection alive even when your app is not running in the foreground won't be feasible, as from Android O, there will be a lot of restrictions on background processes. Also, it will also drain a lot of battery. Best way to handle it would be to send push notification from server.