简体   繁体   中英

How to keep connection alive with Smack XMPP?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM