Doubt about listeners

Hi. I am unsure of where I should place packet listeners. Should it go into the onCreate() method , or in the onStartCommand(), or should it be put into a separate method that runs every few seconds?

My confusion is mostly with the concept of listeners. Is the listener always running and will trigger as soon as a packet is received? Thanks in advance.

Short answer:

No,Yes

Long answer

**
**

You can add it after your connection is established.

Don’t put any xmpp logic in your application activity, you need to create one or more classes to handle it.

For example you can create a XmppManager class so whenever you need something from xmpp you can call

the class

XmppManager.getInstance().Connect();

We will use getInstance() method to insure that we are dealing with same instance.

we will use volatile and synchronized if we will access the instance from different threads (ui thread, service or handler)

Example:

public class **XmppManager **{

public static String HOST = “Server name”;

public static int PORT = 5223;

public static String RESOURCE = “android”;

public XMPPConnection mConnection;

public XmppManager() {

SmackAndroid.init([your application context]);

}

private static volatile XmppManager Instance = null;

public static XmppManager getInstance() {

XmppManager localInstance = Instance;

if (localInstance == null) {

synchronized (XmppManager.class) {

localInstance = Instance;

if (localInstance == null) {

Instance = localInstance = new XmppManager();

}

}

}

return localInstance;

}

//once your connection is Established you can add your listeners

private void onConnectionEstablished(){

PacketFilter filter = new PacketTypeFilter(org.jivesoftware.smack.packet.Message.class);

mConnection.addPacketListener(packetListener, filter);

}

}

You can add it after your connection is established.
To clarify: You can always add listeners in Smack 4.

1 Like

Sorry. It depends on the app logic in my case I do it like that due to my app reconnecting logic.

Thanks Wael I’ll try out the reconnection logic to see how it goes. I have an idea on how to implement it now.