简体   繁体   中英

Android Smack Xmpp connection handling best practices

I've been using Smack XMPP android library for chat application.

My current architecture for chat is ,I use XMPP to send messages to client only if the app is in Foreground otherwise use GCM . Server is already handled properly.

Since android doesn't have method to simply indicate where the app is currently in FG or BG, I find difficult connecting and disconnecting XMPP . So I implemented using timer on each activity onPause and onResume when the app has more than one activities.This is very painful and lot more work to do.

For eg , I have two activities, A and B .Connect XMPP in onResume() of A .Switch from A to B , onPause() will trigger on A and disconnect XMPP connection after 3sec.Within 3sec , onResume() of B will trigger and stop the timer so that connection will be alive . :-)

onPause()

if (Application.getInstance().xmppStatus == XMPPSTATUS.CONNECTED) {
     Application.getInstance().disconnectXmpp(); //disconnect xmpp after 3sec
}

onResume()

if (Application.getInstance().xmppStatus == XMPPSTATUS.DISCONNECTED) {
     LoginHelper.connectXmpp();//connect XMPP 
}

I believe that most of you have fallen into this kind of issue esp in chat so i would very appreciate to hear your experiences on this.

您不应该手动断开客户端的连接,只要在客户端与服务器断开连接时切换到gcm,然后在客户端再次连接时切换回xmpp,所有逻辑都应该在服务器端

The best way is you should use Fragments instead of Activities. If you use fragments then you will have only 1 Activity and your onPause() and onResume() handling will be very easy. Give it a try.... Fragments are more faster than activities.

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