I've got an app with many many services (delivery application for businesses), which connects to an XMPP server to post reports. It's mainly working brilliantly. However, on the odd occasion when connecting over (1/3G) the connection takes too long and the OS kills the app. What's annoying me is that the connection is spawned by a service started by Alarm manager, and I'm using AndroidConnectionConfiguration (aSmack lib), which apparently spawns a seperate thread for connecting to get away from NetworkOnMainUIException. Yet, every so often, my app is still sent a sigabrt signal 6. Why is this happening? I'm not doing anything on the UI, or near it and thought that regardless of time, Android would leave it alone until it was finished or times out itself? Or am I wrong?
Is there anything else I can do to stop this happening? I don't care if XMPP is connected or not, as it will always retry and send when its able, but I can't have the app crashing.
Edit I should say that I'm using aSmack 0.8.10 - And Openfire 3.9.1. But they aren't the problem and work wonderfully well. It's only on the odd occasion that the connection takes too long and Android kills it.
Edit 2 Some code:
package com.goosesys.dta_pta_test.Singletons;
import org.jivesoftware.smack.AndroidConnectionConfiguration;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackAndroid;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import android.content.Context;
import com.google.gson.Gson;
import com.goosesys.dta_pta_test.MessageListenerService;
import com.goosesys.gooselib.Logging;
import com.goosesys.gooselib.Utilities.AppSettings;
import com.goosesys.gooselib.Utilities.Utility;
public class XmppConnector
{
private static XmppConnector instance;
private static boolean isConnected = false;
private static AndroidConnectionConfiguration acc;
private static XMPPConnection xConnection;
private static Context context;
public static void init(Context contxt)
{
if(instance == null)
{
instance = new XmppConnector();
}
context = contxt;
}
public static XmppConnector getInstance()
{
return instance;
}
public static boolean connect() throws XMPPException
{
if(isConnected)
return true;
SmackAndroid.init(context);
acc = new AndroidConnectionConfiguration(AppSettings.XMPP_SERVER_HOST,
AppSettings.XMPP_SERVER_PORT, "Smack");
acc.setSecurityMode(SecurityMode.disabled);
xConnection = new XMPPConnection(acc);
xConnection.addConnectionListener(new ConnectionListener(){
#Override
public void reconnectionSuccessful()
{
Logging.Debug("XmppConnector", "...reconnected to XMPP Server");
}
#Override
public void reconnectionFailed(Exception e)
{
Logging.Debug("XmppConnector", "...reconnection failed: " + e);
}
#Override
public void reconnectingIn(int seconds)
{
Logging.Debug("XmppConnector", "...reconnecting in: " + seconds);
}
#Override
public void connectionClosedOnError(Exception e)
{
Logging.Debug("XmppConnector", "...connection closed on error: " + e);
}
#Override
public void connectionClosed()
{
Logging.Debug("XmppConnector", "...connection closed");
}
});
xConnection.connect();
if(xConnection.isConnected())
{
isConnected = true;
// LOGIN ONCE CONNECTED TO THE SERVER //
xConnection.login(Utility.getAndroidID(context),
AppSettings.XMPP_KEYSTORE_PASSWORD);
// CREATE CHAT MANAGER //
xConnection.getChatManager().addChatListener(new ChatManagerListener(){
#Override
public void chatCreated(final Chat chat, boolean createdLocally)
{
if(!createdLocally)
chat.addMessageListener(new MessageListenerService(context));
}
});
}
else
{
isConnected = false;
}
return isConnected;
}
public static boolean sendMessage(String jsonObj)
{
Message m = new Gson().fromJson(jsonObj, Message.class);
if(m == null)
{
Logging.Error("XmppConnector", "Message object is null.. Aborting");
return false;
}
if(isConnected)
{
xConnection.sendPacket(m);
return true;
}
else
{
return false;
}
}
}
and the small service that kicks it off:
public class BGCollectorProc extends IntentService
{
private DatabaseHelper dbHelper;
public BGCollectorProc()
{
super("BGCollectorProc");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Logging.Debug("BGCollectorProc", "Spinning...");
//dbHelper = DatabaseHelper.getHelper(getApplicationContext());
try
{
// initialise the connection
XmppConnector.init(this);
// get the static reference
XmppConnector.getInstance();
// connect to the server
if(XmppConnector.connect())
{
Logging.Info("BGCollectorProc", "CONNECTED TO XMPP SERVER");
}
}
catch(XMPPException e)
{
e.printStackTrace();
}
/*
// Worker thread area //
try {
postDeliveries();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
postGeoLogs();
*/
return Service.START_NOT_STICKY;
}
Cheers.
SIGABRT usually means that something fatal has happened within dalvik. It's not Android ActivityManager that kills your process. It's the VM that terminates itself because of a VM fault. Usually there will be more information about the fault. Maybe you didn't recognize the logs as related to the SIGABRT. At least I would expect to find some more information about the cause of the SIGABRT in the logs.
BTW: A service that holds an active XMPPConnection is an ideal candidate for a sticky Android service, that should be running as long as the XMPPConnection should be active.
Related
I've a Service to manage my MQTT Client connection, the MQTT works fine, but the problem is when I restart Broker Server, the Android client not reconnect. A exception is triggered on onConnectionLost() callback.
Notes
I'm using Moquette Broker at same computer -> Moquette
I've two Android clients app, a using Service (the problematic) and other working on a Thread, without Service (this works fine, reconnect is ok).
I can't run the Android Client MQTT lib, because this I'm using the Eclipse Paho MQTT.
Yes, I make setAutomaticReconnect(true);
Problem
The Android app that use Service, to works forever, not reconnect to MQTT Broker.
Code
MQTTService.java
public class MQTTService extends Service implements MqttCallbackExtended {
boolean running;
private static final String TAG = "MQTTService";
public static final String ACTION_MQTT_CONNECTED = "ACTION_MQTT_CONNECTED";
public static final String ACTION_MQTT_DISCONNECTED = "ACTION_MQTT_DISCONNECTED";
public static final String ACTION_DATA_ARRIVED = "ACTION_DATA_ARRIVED";
// MQTT
MqttClient mqttClient;
final String serverURI = "tcp://"+ServidorServices.IP+":1883";
final String clientId = "Responsavel";
String topicoId;
Thread mqttStartThread;
public boolean subscribe(String topic) {
try {
Log.i(TAG,"Subscripe: " + topic);
mqttClient.subscribe(topic);
mqttClient.subscribe("LOCATION_REAL");
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// Life Cycle
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG,"onBind()");
return null;
}
#Override
public void onCreate() {
Log.d(TAG,"onCreate()");
running = true;
topicoId = getSharedPreferences("myprefs",MODE_PRIVATE).getString("tag_id_aluno","0");
mqttStartThread = new MQTTStartThread(this);
if(topicoId.equals("0")) {
Log.i(TAG,"Error to subscribe");
return;
}
mqttStartThread.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
class MQTTStartThread extends Thread {
MqttCallbackExtended mqttCallbackExtended;
public MQTTStartThread(MqttCallbackExtended callbackExtended) {
this.mqttCallbackExtended = callbackExtended;
}
#Override
public void run() {
try {
mqttClient = new MqttClient(serverURI,clientId,new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(true);
options.setCleanSession(true);
mqttClient.setCallback(mqttCallbackExtended);
mqttClient.connect();
} catch (Exception e) {
Log.i(TAG,"Exception MQTT CONNECT: " + e.getMessage());
e.printStackTrace();
}
}
}
#Override
public void onDestroy() {
Log.d(TAG,"onDestroy()");
running = false;
if (mqttClient != null) {
try {
if (mqttClient.isConnected()) mqttClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public boolean onUnbind(Intent intent) {
Log.i(TAG,"onUnbind()");
return super.onUnbind(intent);
}
// Callbacks MQTT
#Override
public void connectComplete(boolean reconnect, String serverURI) {
Log.i(TAG,"connectComplete()");
if (topicoId == null) {
Log.i(TAG,"Erro ao ler ID da Tag");
return;
}
sendBroadcast(new Intent(ACTION_MQTT_CONNECTED));
subscribe(topicoId);
}
#Override
public void connectionLost(Throwable cause) {
Log.i(TAG,"connectionLost(): " + cause.getMessage());
cause.printStackTrace();
sendBroadcast(new Intent(ACTION_MQTT_DISCONNECTED));
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i(TAG,"messageArrived() topic: " + topic);
if (topic.equals("LOCATION_REAL")) {
Log.i(TAG,"Data: " + new String(message.getPayload()));
} else {
Context context = MQTTService.this;
String data = new String(message.getPayload());
Intent intent = new Intent(context,MapsActivity.class);
intent.putExtra("location",data);
LatLng latLng = new LatLng(Double.valueOf(data.split("_")[0]),Double.valueOf(data.split("_")[1]));
String lugar = Utils.getAddressFromLatLng(latLng,getApplicationContext());
NotificationUtil.create(context,intent,"Embarque",lugar,1);
if (data.split("_").length < 3) {
return;
}
double latitude = Double.valueOf(data.split("_")[0]);
double longitude = Double.valueOf(data.split("_")[1]);
String horario = data.split(" ")[2];
Intent iMqttBroadcast = new Intent(ACTION_DATA_ARRIVED);
iMqttBroadcast.putExtra("topico",String.valueOf(topic));
iMqttBroadcast.putExtra("latitude",latitude);
iMqttBroadcast.putExtra("longitude",longitude);
iMqttBroadcast.putExtra("evento","Embarcou");
iMqttBroadcast.putExtra("horario",horario);
sendBroadcast(iMqttBroadcast);
}
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.i(TAG,"deliveryComplete()");
}
}
Exception Stacktrace
I/MQTTService: connectionLost(): Connection lost
W/System.err: Connection lost (32109) - java.io.EOFException
W/System.err: at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:146)
W/System.err: at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: java.io.EOFException
W/System.err: at java.io.DataInputStream.readByte(DataInputStream.java:77)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.wire.MqttInputStream.readMqttWireMessage(MqttInputStream.java:65)
W/System.err: at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:107)
W/System.err: ... 1 more
I think you forgot to include MqttConnectOptions with MqttClient object.
Please try like following
mqttClient.connect(options);
instead of
mqttClient.connect();
Hope it may help to resolve your re-connect issue.
As method description says.
options.setAutomaticReconnect(true);
The client will attempt to reconnect to the server. It will initially wait 1 second before it attempts to reconnect, for every failed reconnect attempt, the delay will doubleuntil it is at 2 minutes at which point the delay will stay at 2 minutes.
Another option would be you could manage retry interval in case of connection lost events.
I am creating an application that will monitor movements in a particular Android device (client) and report such instances to another Android device (server). Also, under specific conditions, the client will take a picture and transmit the image to the server.
I am using WiFi direct to setup the connection between the two devices. After that I am using socket connections as explained in the WiFi Direct Demo. I am using port 8988 to send the motion sensor events and I am using port 8987 to send the images capture.
On the server side, I am using two different instances of the same Async Task with serversocket connecting to different ports to listen for the incoming messages. Everything works fine as long as only the motion sensor events are being sent across. The first image capture is also being sent/received correctly. However, after that the server doesn't receive any additional messages. I tried having two different Async Task classes to avoid having two instances of the same class but that didn't work as well. I also tried having one as an Async Task and another as an Intent Service but even that doesn't work.
This is IntentService I am using to send the messages across to the server.
public class MessageSender extends IntentService {
public static final String EXTRAS_TIMEOUT = "timeout";
public static final String EXTRAS_ADDRESS = "go_host";
public static final String EXTRAS_PORT = "go_port";
public static final String EXTRAS_DATA = "data";
private Handler handler;
public MessageSender(String name) {
super(name);
}
public MessageSender() {
super("MessageTransferService");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
return super.onStartCommand(intent, flags, startId);
}
#Override
protected void onHandleIntent(Intent intent) {
String host = intent.getExtras().getString(EXTRAS_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_PORT);
byte[] data = intent.getExtras().getByteArray(EXTRAS_DATA);
int timeout = intent.getExtras().getInt(EXTRAS_TIMEOUT);
try {
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), timeout);
OutputStream stream = socket.getOutputStream();
stream.write(data);
} catch (final IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Exception has occurred: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
/*handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Socket Connection closed now..",
Toast.LENGTH_SHORT).show();
}
});*/
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
This is Async Task on the server that starts listeners on two ports (8987 and 8988) to receiver the information of motion sensor events and images.
public class MessageReceiver extends AsyncTask<Void, Void, String> {
private Context context;
private int port;
private Bitmap mBitmap;
public MessageReceiver(Context context, int port) {
this.context = context;
this.port = port;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(port);
Socket client = serverSocket.accept();
InputStream inputstream = client.getInputStream();
String returnString = "";
if (port == MainActivity.PORT_SENSOR_COMM) {
// do something
} else if (port == MainActivity.PORT_IMAGE_COMM) {
//do something
}
serverSocket.close();
return returnString;
} catch (Exception e) {
return "Exception Occurred:" + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
boolean startNewTask = true;
if (port == MainActivity.PORT_SENSOR_COMM) {
//do something
} else if (port == MainActivity.PORT_IMAGE_COMM) {
//do something
}
//doing this to start listening for new messages again
new MessageReceiver(context, port).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
protected void onPreExecute() {
}
}
I am now wondering whether Android WiFiDirect allows parallel communication between two devices on different ports. Searched the docs but could'nt find much help. What I am doing wrong? What is the correct method to accomplish what I am trying to do? Any help would be greatly appreciated. Thanks for looking.
I am trying to create a basic chat app using asmack and Openfire.
I have created a bound service for the XMPPConnection and each Activity binds to it.
Whenever I try to bind to a Service there is a very long delay. I know that the bindService is asynchronous but I want to be certain that my implementation of the Service is correct before I begin looking elsewere for problems.
I bind my Service in the onCreate method and try to access the connection in the onStart.
I am still new to this but I suspect that I have done something wrong thread-wise. The way my app runs now, the mBound variable returns true only if I try to access it from an OnClickListener. What is it that happens in the Listener that makes such a big difference? I tried to find the code for the OnClick method but I couldn't find it.
My XMPPConnectionService is this:
package com.example.smack_text;
import java.io.File;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class XMPPService extends Service{
XMPPConnection connection;
// private final IBinder mBinder = new LocalBinder();
#Override
public void onCreate(){
super.onCreate();
Log.d("service","created");
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
#Override
public IBinder onBind(Intent intent) {
Log.d("sevice","bound");
LocalBinder mBinder = new LocalBinder (this);
return mBinder;
}
public class LocalBinder extends Binder {
XMPPService service;
public LocalBinder (XMPPService service)
{
this.service = service;
}
public XMPPService getService (){
return service;
}
// XMPPService getService() {
// return XMPPService.this;
// }
}
public void connect(final String user, final String pass) {
Log.d("Xmpp Alex","in service");
ConnectionConfiguration config = new ConnectionConfiguration("10.0.2.2",5222);
// KEYSTORE SETTINGS
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
config.setTruststoreType("AndroidCAStore");
config.setTruststorePassword(null);
config.setTruststorePath(null);
}
else {
config.setTruststoreType("BKS");
String path = System.getProperty("javax.net.ssl.trustStore");
if (path == null)
path = System.getProperty("java.home") + File.separator + "etc"
+ File.separator + "security" + File.separator
+ "cacerts.bks";
config.setTruststorePath(path);
}
// Create XMPP Connection
connection = new XMPPConnection(config);
new Thread(new Runnable() {
#Override
public void run() {
try {
connection.connect();
connection.login(user, pass);
if(connection.isConnected()){
Log.d("Alex", "connected biatch!");
}
else{
Log.d("Alex","not connected");
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
public void disconnect(){
if(connection.isConnected()){
connection.disconnect();
}
else{
Toast.makeText(getApplicationContext(), "not connected", Toast.LENGTH_LONG).show();
}
}
}
I implement an Android Chat with Asmack.
I have created a Service.
The service has a global variable with the XmppConnection.
At the begining i use the thread for connect and login.
then I set VCard for logged user, set rosterListener
finally set connection.addPacketListener
I update the activities with a BroadcastReceiver activity side and
#Override
public IBinder onBind(Intent arg0) {
return mBinderXmpp;
}
public class BinderServiceXmpp extends Binder {
ServiceXmpp getService() {
return ServiceXmpp.this;
}
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayInfo();
handler.postDelayed(this, 2000); // 2 segundos
}
};
private void DisplayInfo() {
isRunning = true; // flag to know if service is running
Intent tempIntent;
tempIntent = new Intent(BROADCAST_ACTION);
tempIntent.putExtra("UPDATE_OPTION", UPDATE_ACTION);
sendBroadcast(tempIntent);
}
Your implementation works, you still need to implement the handler for the actions like CONNECT and DISCONNECT from your clients bound (LoginActivity for instance).
Example:
class IncomingHandler extends Handler { // Handler of incoming messages from clients bound.
#Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case MSG_CONNECT_XMPP:
new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... params) {
// Do connection
}
#Override
protected void onPostExecute(Boolean aBoolean) {
// Notify the connection status
}
}.execute();
break;
case MSG_DICCONNECT_XMPP:
new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... params) {
// Do disconnection
}
#Override
protected void onPostExecute(Boolean aBoolean) {
// Notify the connection status
}
}.execute();
break;
default:
super.handleMessage(msg);
}
}
}
But, this approach of creating an AsyncTask anytime the Service needs to run a network action will reach its limit for the sendBroadcast in a BroadcastReceiver.
If you have BroadcastReceiver that needs to start or stop the connection by sending a message to the XMPPService, you have something like this:
public class NetworkConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo network = cm.getActiveNetworkInfo();
network = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (XmppService.isRunning() && network.isConnected()) {
context.sendBroadcast(new Intent(XmppService.ACTION_CONNECT));
} else if (XmppService.isRunning() && !network.isConnected()) {
context.sendBroadcast(new Intent(XmppService.ACTION_DISCONNECT));
}
}
}
Then, you will need to implement a Broadcast listener in the XmppService class.
But, you CANNOT run an AsyncTask in a Broadcast listener!
The remain options are described in my post here:
Android - Best option to implement Networking Class
I use asmack-android-7-beem library for Android. I have a background service running, such as my app stays alive. But sooner or later XMPP connection dies without any notice. The server says that the client is still online but no packets are sent or received.
For example the client doesn't receive any presence packets when other clients have a new presence. I have XMPPConnection as an attibute of my main Application class.
I set ConnectionConfiguration config.setReconnectionAllowed(true) before the connection was made.
But reconnection doesn't happen. XMPPConnection connection.isConnected() returns true.
So the client is not aware that connection is actually lost.
Is there any way to keep the connection alive?
When using asmack put some code like this in your app to make Dalvik load the ReconnectionManager class and run it's static initialization block:
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
Actually There is not any problem with Reconnection manager. First you need to add connection listener to your connection manager.
connection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
Log.i("","Successfully reconnected to the XMPP server.");
}
#Override
public void reconnectionFailed(Exception arg0) {
Log.i("","Failed to reconnect to the XMPP server.");
}
#Override
public void reconnectingIn(int seconds) {
Log.i("","Reconnecting in " + seconds + " seconds.");
}
#Override
public void connectionClosedOnError(Exception arg0) {
Log.i("","Connection to XMPP server was lost.");
}
#Override
public void connectionClosed() {
Log.i("","XMPP connection was closed.");
}
});
if any error occurred the connectionClosedOnError(Exception arg0) will automatically called
when connection is closed
public void connectionClosed() {
Log.i("","XMPP connection was closed.");
//You can manually call reconnection code if you want to reconnect on any connection close
}
then check it this will call reconnectingin() method and try to reconnect.
Hope so this will help you.
use below code for check connection
PingManager pingManager = PingManager.getInstanceFor(connection); pingManager.setPingInterval(5000);
add listner for ping fail handling to handle connection is connected or not because isConnected method is not reliable for check state of connection.
pingManager.registerPingFailedListener(PingFailedListener);
For mobile network connectivity is very big problem so you need to check network connectivity for mobile using broadcast receiver and on data reconnection you can use pingMyServer method to check connection is alive or not, if you are getting ping reply from server, means connection is alive otherwise on ping fail you can reconnect connection manually.
Here's my code work fine for ReconnectionManager
1) Add addConnectionListener on xmpp connection
XMPPConnectionListener mConnectionListener = new XMPPConnectionListener(username);
connection.addConnectionListener(mConnectionListener);
2) if connection closed then reconnect automatically using ReconnectionManager class
ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection);
reconnectionManager.enableAutomaticReconnection();
reconnectionManager.setEnabledPerDefault(true);
3) ConnectionListener for reconnect, connect and authenticated on server. if connection authenticated successfully with server also register PingManager and ServerPingWithAlarmManager class.
public class XMPPConnectionListener implements ConnectionListener {
String username="";
public XMPPConnectionListener(String username){
this.username=username;
}
#Override
public void connected(final XMPPConnection connectionObeject) {
sendPresenceAvailable();
Log.d(TAG, "xmpp Connected()");
connected = true;
}
#Override
public void connectionClosed() {
Log.d(TAG, "xmpp ConnectionCLosed()");
isAuthenticatedPreviouly=false;
connected = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
Log.d(TAG, "xmpp ConnectionClosedOnError() :"+System.currentTimeMillis());
isAuthenticatedPreviouly=false;
connected = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d(TAG, "xmpp reconnectingIn() :"+System.currentTimeMillis());
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
Log.d(TAG, "xmpp ReconnectionFailed!");
connected = false;
// chat_created = false;
loggedin = false;
try {
connection.connect();
} catch (SmackException | IOException | XMPPException | InterruptedException exception) {
exception.printStackTrace();
}
}
#Override
public void reconnectionSuccessful() {
Log.d(TAG, "xmpp ReconnectionSuccessful");
connected = true;
sendPresenceAvailable();
loggedin = false;
}
#Override
public void authenticated(XMPPConnection connection2, boolean resumed) {
Log.d(TAG, "xmpp Type Main Authenticated() :" + connection.isAuthenticated());
if(connection.isAuthenticated()) {
ServerPingWithAlarmManager.getInstanceFor(connection).setEnabled(true);
PingManager pingManager = PingManager.getInstanceFor(connection);
pingManager.setPingInterval(10);
try {
pingManager.pingMyServer();
pingManager.pingMyServer(true,10);
pingManager.pingServerIfNecessary();
pingManager.registerPingFailedListener(new PingFailedListener() {
#Override
public void pingFailed() {
Log.d("Ping","pingFailed");
disconnect();
connect();
}
});
registerAllListener();
}
}
I have the same problem, except that My program run on server side JVM.
I used smack 4.0 in the first place. Then I updated to smack 4.1, but the problem still happened. Finally I found a configuration module: PingManager
After using this, the occurrence of this situation was drop down.
connection = new XMPPTCPConnection(config);
PingManager pingManager = PingManager.getInstanceFor(connection);
pingManager.setPingInterval(300); // seconds
In Smack 4.1, I use ServerPingWithAlarmManager. You can find more details about keeping connection alive ramzandroid blog here.
For these case you need to handle the disconnection manually I mean you should intercept any disconnection, connection listener notified when you got a disconnection over.
public void connectionClosedOnError(Exception exception)
import android.util.Log;
import com.dagm8.core.protocols.ConnectionState;
import com.dagm8.core.service.XMPPService;
import com.dagm8.events.ConnectionStateEvent;
import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import java.io.IOException;
import static com.dagm8.core.protocols.ConnectionState.CONNECTED;
import static com.dagm8.core.protocols.ConnectionState.DISCONNECTED;
import static com.dagm8.core.protocols.ConnectionState.RECONNECTING;
/**
* dagm8-android
* Created by Bedoy on 8/28/17.
*/
public class ConnectionController implements ConnectionListener {
private String TAG = getClass().getCanonicalName();
private XMPPTCPConnection mConnection;
public void setConnection(XMPPTCPConnection connection) {
mConnection = connection;
}
public void init(XMPPTCPConnection connection) throws InterruptedException, XMPPException, SmackException, IOException {
setConnection(connection);
mConnection.setPacketReplyTimeout(10000);
mConnection.addConnectionListener(this);
mConnection.connect();
}
#Override
public void connected(XMPPConnection connection) {
XMPPService.connectionState = RECONNECTING;
notifyConnectionState(RECONNECTING);
try {
mConnection.login();
} catch (XMPPException | SmackException | IOException | InterruptedException e) {
e.printStackTrace();
}
Log.i(TAG, "connected()");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
XMPPService.connectionState = CONNECTED;
notifyConnectionState(CONNECTED);
Log.i(TAG, "authenticated()");
}
#Override
public void connectionClosed() {
XMPPService.connectionState = DISCONNECTED;
notifyConnectionState(DISCONNECTED);
Log.i(TAG, "connectionClosed()");
}
#Override
public void connectionClosedOnError(Exception e) {
XMPPService.connectionState = DISCONNECTED;
notifyConnectionState(DISCONNECTED);
try {
mConnection.connect();
} catch (SmackException | IOException | XMPPException | InterruptedException exception) {
exception.printStackTrace();
}
Log.i(TAG, "connectionClosedOnError()");
}
#Override
public void reconnectingIn(int seconds) {
XMPPService.connectionState = RECONNECTING;
notifyConnectionState(RECONNECTING);
Log.i(TAG, "reconnectingIn()");
}
#Override
public void reconnectionSuccessful() {
XMPPService.connectionState = CONNECTED;
notifyConnectionState(CONNECTED);
Log.i(TAG, "reconnectionSuccessful()");
}
#Override
public void reconnectionFailed(Exception e) {
XMPPService.connectionState = DISCONNECTED;
notifyConnectionState(DISCONNECTED);
Log.i(TAG, "reconnectionFailed()");
}
private void notifyConnectionState(ConnectionState state) {
EventBus.getDefault().post((ConnectionStateEvent) () -> state);
}
public boolean isAuthenticated()
{
return mConnection.isAuthenticated();
}
public void login() {
try {
mConnection.login();
} catch (XMPPException | SmackException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
I want to test my bound service with ServiceTestCase.
The testing consists of binding to MyBindServer, and sending a Message.
Watching the logs, you can see the service is started when onBind() is called,
and a message is sent from testAHello(), but, the server's handleMessage() is never called.
From the logs:
I/TestRunner( 2099): started: testAHello(com.inthinc.mybindserver.test.MyBindServerTest)
I/MyBindServerTest( 2099): setUp()
I/MyBindServer( 2099): onBind, action=com.inthinc.mybindserver.START
I/MyBindServerTest( 2099): testAHello
I/MyBindServerTest( 2099): sending SAY_HELLO
[here is where I expect to see the output from handleMessage()]
I/MyBindServerTest( 2099): tearDown()
I/TestRunner( 2099): finished:testAHello(com.inthinc.mybindserver.test.MyBindServerTest)
I/TestRunner( 2099): passed: testAHello(com.inthinc.mybindserver.test.MyBindServerTest)
Here is the code for MyBindServer.java:
package com.inthinc.mybindserver;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
public class MyBindServer extends Service {
static final String TAG = "MyBindServer";
public static final int MSG_SAY_HELLO = 1;
final Messenger mMessenger = new Messenger(new IncomingHandler());
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
Log.i(TAG, String.format("handleMessage, what=%d", msg.what));
switch (msg.what) {
case MSG_SAY_HELLO:
Log.i(TAG, "hello");
break;
default:
super.handleMessage(msg);
}
}
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, String.format("onBind, action=%s", intent.getAction()));
return mMessenger.getBinder();
}
}
Here is the code for MyBindServerTest.java:
package com.inthinc.mybindserver.test;
import com.inthinc.mybindserver.MyBindServer;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.test.ServiceTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
public class MyBindServerTest extends ServiceTestCase<MyBindServer> {
private static final String TAG = "MyBindServerTest";
Messenger mServer = null;
public MyBindServerTest() {
super(MyBindServer.class);
}
public MyBindServerTest(Class<MyBindServer> serviceClass) {
super(serviceClass);
}
#Override
public void setUp() {
try {
super.setUp();
Log.i(TAG, "setUp()");
Intent bindIntent = new Intent("com.inthinc.mybindserver.START");
IBinder binder = bindService(bindIntent);
assertNotNull(binder);
mServer = new Messenger(binder);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void tearDown() {
try {
super.tearDown();
Log.i(TAG, "tearDown()");
} catch (Exception e) {
e.printStackTrace();
}
}
#SmallTest
public void testAHello() {
Log.i(TAG, "testAHello");
assertNotNull(mServer);
Message msg = Message.obtain(null, MyBindServer.MSG_SAY_HELLO);
Log.i(TAG, "sending SAY_HELLO");
try {
mServer.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
I was able to get this working using the procedure below..anyone is welcome to chime in if this is incorrect, but the example above works (i.e. MyBindServer's handler receives messages)
It seems as though ServiceTestCase's bindService() method intends to act like a local service. In this case, the goal is to test as a separate process, which means using the following instead of ServiceTestCase's bindService:
Intent bindIntent = new Intent(<registered intent>); //Where registered intent is declared in the manifest file
getContext().bindService(bindIntent,mConn,Context.BIND_AUTO_CREATE);
where mConn is a ServiceConnection object implemented to do whatever your test needs it to do, in the case above, set mServer.
With the above, MyBindServer's handleMessage() is called for the testAHello() test.
UPDATE: I have noticed that depending on how quickly the test processing is done, teardown() can be called before the binding is ready to use. In the case above adding control variables to throttle the program flow based on mConn's onServiceConnected being called provided consistent results.
E.g.
protected boolean bound = false;
protected boolean processed = false;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
Log.i(TAG,"Service conn");
mServer = new Messenger(service);
if(mServer != null
&& mServer != null){
bound = true;
}
processed = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Log.i(TAG,"Service Disconn");
}
};
Then add:
while(!processed){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
to testAHello()