如何使用smack添加好友?

时间:2015-10-13 03:38:13

标签: java openfire smack

我想知道如何确认添加朋友的请求。

Smack Version 4.1.1

据我所知,

roster = Roster.getInstanceFor(con);
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
roster.createEntry(targetUser, nickname, new String[] {"friends"});

将在数据库中创建一个名单,并向targetUser发送一个节请求。 我的节听众如下:

StanzaListener callback = new StanzaListener() {
        @Override
        public void processPacket(Stanza stanza) throws NotConnectedException {
            // TODO Auto-generated method stub
            String head = con.getUser() + " : ";
            System.out.println(head + "Got the presence stanza");
            if(((Presence)stanza).getType().equals(Presence.Type.subscribe)) {
                Presence subscribed = new Presence(Presence.Type.subscribed);
                subscribed.setTo(stanza.getFrom());
                System.out.println(head + subscribed.getFrom());
                subscribed.setFrom(stanza.getTo());
                con.sendStanza(subscribed);

                if( ! roster.contains(stanza.getFrom())) {
                    System.out.println(head + "Friend added.");
                    addFriend(stanza.getFrom(),"computer");
                }

            } else {
                System.out.println(head + "Subscribed received from " + stanza.getFrom());
                if(roster.contains(stanza.getFrom())) {
                    System.out.println(head + "OK");
                }
            }
        }
    };

它不起作用,我想知道targetUser何时收到节请求,如何发送回调存在(或其他)以确认或批准或同意? 如何添加朋友?

1 个答案:

答案 0 :(得分:0)

试试这个:

public void addFriend(User usuario) {
        if (APDApplication.connection != null && APDApplication.connection.isConnected()) {
            try {
                Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
                Roster roster = Roster.getInstanceFor(APDApplication.connection);

                if (!roster.contains(usuario.getChatId())) {
                    roster.createEntry(usuario.getChatId() + "@jabber/Smack", usuario.getName(), null);
                } else {
                    logManager.error("Contacto ya existente en la libreta de direcciones");
                }

            } catch (SmackException.NotLoggedInException e) {
                e.printStackTrace();
            } catch (SmackException.NoResponseException e) {
                e.printStackTrace();
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
            } catch (XMPPException.XMPPErrorException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

希望这可以帮助你!!