2
votes

I'm creating a chat application in Android, using Smack 4.1. I have implemented an IntentService that creates the connection and log the user in xmpp once the user logs in the application. I am using the following code to start the intentservice from a fragment, that works fine:

chatIntent = new Intent(mContext, ChatService.class);
chatIntent.setAction(XMPP_ACTION_CONNECT);
mContext.startService(chatIntent);

Then I'm trying to send a message from the fragment. I've tried to use the same code as above

Intent sendmsgIntent = new Intent(mContext, ChatService.class);
sendmsgIntent.putExtra("msg",messageText);
sendmsgIntent.putExtra("to",companionLabel.getText().toString());
sendmsgIntent.setAction(ACTION_SEND_MESSAGE);
mContext.startService(sendmsgIntent);

but when the intent is received in IntentService, the XMPPTCPConnection connection is null and I cannot use the:

connection.sendStanza(message);

Why is this null? Does the service start again from the beginning? Is this way I'm using to send the second intent wrong? Or how could I get the XMPPTCPConnection connection that was created when the first intent was sent?

1

1 Answers

2
votes

Yes, the IntentService just executes onHandleIntent in a background thread and is then destroyed.

Instead use a normal Service which can be bound from Fragments and Activities to keep it available for their lifecycle; there's actually some decent documentation for that: http://developer.android.com/guide/components/bound-services.html#Binding The Service will run on the UI thread so you'll need to execute your Smack network calls in a new Thread or in AsyncTasks.