I'm using aSmack and Openfire for my application. And Spark for testing.
I'm writing my connection code and broadcast receiver which listen network state in STICKY service.
When i turn off my wifi, internet goes off but Spark still show me as 'Available' and after 3-4 minutes it turns my status to 'unavailable'.
I tried xmppConnection.disconnect() and Presence.Type.unavailable. But none of them working for me.
How can i instantly disconnect XMPP server / send presence 'Unavailable' after disconnecting client's internet connection ?
This is my code:
// Connect XMPP Server
public void connectXMPPServer() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// Create a connection
ConnectionConfiguration connConfig = new ConnectionConfiguration(
HOST, PORT, SERVICE);
connConfig.setReconnectionAllowed(true);
xmppConnection = new XMPPConnection(connConfig);
try {
xmppConnection.connect();
Log.i("XMPPChatDemoActivity", "Connected to "
+ xmppConnection.getHost());
} catch (XMPPException ex) {
Log.e("XMPPChatDemoActivity", "Failed to connect to "
+ xmppConnection.getHost());
Log.e("XMPPChatDemoActivity", ex.toString());
}
try {
if (xmppConnection.isConnected()) {
xmppConnection.login(USERNAME, PASSWORD);
Log.i("XMPPChatDemoActivity", "Logged in as "
+ xmppConnection.getUser());
Presence presence = new Presence(
Presence.Type.available);
xmppConnection.sendPacket(presence);
}
} catch (XMPPException ex) {
Log.e("XMPPChatDemoActivity", "Failed to log in as "
+ USERNAME);
Log.e("XMPPChatDemoActivity", ex.toString());
}
}
});
t.start();
}
// Broadcast receiver; listens to network state
public BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
if (isNetworkOn()) {
Log.i("BackgroundService-BroadcastReceiver",
"Network is on");
connectXMPPServer();
} else if (!isNetworkOn()) {
Log.i("BackgroundService-BroadcastReceiver",
"Network is off");
Presence presence = new Presence(Presence.Type.unavailable);
xmppConnection.sendPacket(presence);
xmppConnection.disconnect();
}
} catch (Exception e) {
Log.e("BackgroundService-networkStateReceiver", e.toString());
}
}
};
// Returns network state
public boolean isNetworkOn() {
ConnectivityManager connMngr = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connMngr.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}