有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用smack添加好友?

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

Smack版本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) 个答案

  1. # 1 楼答案

    试试这个:

    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();
                }
            }
        }
    

    希望这对你有帮助