How To Know Online Or Offline Of User In Smack In One To One Chat?

- 1 answer

I have tried this code and all the snippet available still cannot able to receive the online or offline presence of the user. Please help me. Thanks in advance.

fun checkStatus() {
    val jid = JidCreate.entityBareFrom("[email protected]")

    var roster = Roster.getInstanceFor(connection)
    var availability = roster.getPresence(jid);
    var  userMode = availability.getMode();
    retrieveState_mode(userMode, availability.isAvailable)

fun retrieveState_mode(userMode: Presence.Mode, isOnline:Boolean):Int {
    var userState = 0;
    if(userMode == Presence.Mode.dnd) {
        userState = 3;
    } else if (userMode == Presence.Mode.away || userMode == Presence.Mode.xa) {
        userState = 2;
    } else if (isOnline) {
        userState = 1;
    return userState

Always I'm getting as 0



First thing first. If you read this:

you will find this: subscription='both': You and the contact are interested in each other's presence information.

So if your roster is set to subscription='both', you both must be in each other roster (lets say buddy request and approval in both directions) to listen to each others presence information.

So knowing previous, the way I have done it using Smack is:

//Created presence packet listener
private StanzaListener presencePacketListener;

//In my connection creating
private XMPPTCPConnection createConnection() throws XmppStringprepException {
        XMPPTCPConnectionConfiguration.Builder config =  XMPPTCPConnectionConfiguration.builder();
        return new XMPPTCPConnection(;

//Then in login method
public void login() throws SmackInvocationException, XmppStringprepException {
        try {
            //Add presencePacketListener to listen for subscribed users (Roster) presence
            con.addSyncStanzaListener(presencePacketListener, new StanzaTypeFilter(Presence.class));
            //Actual login
        } catch(Exception e) {          
            throw exception;

// onConnectionEstablished method
private void onConnectionEstablished() {
        if (state != State.CONNECTED) {         
            sendPacket(new Presence(Presence.Type.available));

When doing

sendPacket(new Presence(Presence.Type.available));

all users in your roster subscription will receive this presence packet. That will be processed in


that we have registered earlier on login.

public class PresencePacketListener implements StanzaListener {
    private Context context;

    PresencePacketListener(Context context) {
        this.context = context;

    public void processStanza(Stanza packet) {
        Presence presence = (Presence)packet;
        Presence.Type presenceType = presence.getType();
        //Do sth with presence