首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用PubNub获取用户状态

使用PubNub获取用户状态
EN

Stack Overflow用户
提问于 2016-09-13 16:11:31
回答 1查看 688关注 0票数 0

我已经创建了一个应用程序,实现应用程序调用使用Sinch。只有当调用方知道收件人的名称时,它才能工作。

为了克服这个问题,Sinch建议使用PubNub获取用户状态。他们也有一个这里的教程。,问题是教程很老了,PubNub从那时起就更新了他们的API。我试着使用他们自己的文档使用他们的新API来实现这些功能,但是它不起作用,或者更准确地说,我不知道如何去做。

我目前的代码是:

代码语言:javascript
运行
复制
public class LoggedUsers extends Activity {
    private PubNub pubNub;
    String name;
    private ArrayList users;
    private JSONArray loggedUserList;
    ListView UserList;
    TextView allUsers;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_list);
        allUsers = (TextView) findViewById(R.id.JSONFromPubNub);
        SharedPreferences sp = getSharedPreferences("User_Details", MODE_APPEND);
        try {
            name = sp.getString("UserName", "");
        } catch (NullPointerException e) {

        }
        final PNConfiguration pnc = new PNConfiguration();
        pnc.setPublishKey("publish key");
        pnc.setSubscribeKey("subscribe key");
        pnc.setUuid(name);

        pubNub = new PubNub(pnc);
        users = new ArrayList<String>();
        UserList = (ListView) findViewById(R.id.listView);
        String user = getUserStatus();
        allUsers.setText(user);
        final ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), R.layout.single_item_list, users);
        UserList.setAdapter(adapter);

        pubNub.addListener(new SubscribeCallback() {
            @Override
            public void status(PubNub pubnub, PNStatus status) {
                if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
                    // This event happens when radio / connectivity is lost
                    HashMap <String,String> map = new HashMap();
                    map.put("State","Offline");
                    pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
                } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {

                    // Connect event. You can do stuff like publish, and know you'll get it.
                    // Or just use the connected event to confirm you are subscribed for
                    // UI / internal notifications, etc
                    HashMap <String,String> map = new HashMap();
                    map.put("State","Online");
                    pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
                  /*  if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                        pubnub.publish().channel("awesomeChannel").message("hello!!").async(new PNCallback<PNPublishResult>() {
                            @Override
                            public void onResponse(PNPublishResult result, PNStatus status) {
                                // Check whether request successfully completed or not.
                                if (!status.isError()) {

                                    // Message successfully published to specified channel.
                                }
                                // Request processing failed.
                                else {

                                    // Handle message publish error. Check 'category' property to find out possible issue
                                    // because of which request did fail.
                                    //
                                    // Request can be resent using: [status retry];
                                }
                            }
                        });
                    }*/
                } else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
                    HashMap <String,String> map = new HashMap();
                    map.put("State","Online");
                    pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());

                    // Happens as part of our regular operation. This event happens when
                    // radio / connectivity is lost, then regained.
                } else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {

                    // Handle messsage decryption error. Probably client configured to
                    // encrypt messages and on live data feed it received plain text.
                }
            }

            @Override
            public void message(PubNub pubnub, PNMessageResult message) {

            }

            @Override
            public void presence(PubNub pubnub, PNPresenceEventResult presence) {

            }
        });
    }
    public String getUserStatus(){
        final StringBuilder allUsers = new StringBuilder();
        pubNub.subscribe().channels(Arrays.asList("CallingChannel1")).withPresence().execute();
        pubNub.hereNow()
                // tailor the next two lines to example
                .channels(Arrays.asList("CallingChannel1"))
                .includeState(true)
                .includeUUIDs(true)
                .async(new PNCallback<PNHereNowResult>() {
                    @Override
                    public void onResponse(PNHereNowResult result, PNStatus status) {
                        if (status.isError()) {
                            // handle error
                            return;
                        }

                        for (PNHereNowChannelData channelData : result.getChannels().values()) {
                            allUsers.append("---");
                            allUsers.append("channel:" + channelData.getChannelName());
                            allUsers.append("occoupancy: " + channelData.getOccupancy());
                            allUsers.append("occupants:");
                            for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
                                allUsers.append("uuid: " + occupant.getUuid() + " state: " + occupant.getState());
                            }
                        }
                    }
                });
               return allUsers.toString();
    }



    @Override
    protected void onResume() {
        super.onResume();
    }
}

以下是我的问题:

  1. 我试图在文本视图中显示我收到的所有数据(稍后,它将安排在一个列表视图或回收器视图中),但是我得到了一个空白屏幕,所以我从服务器获得null。
  2. 应该不断更新用户状态,以了解用户是否更改状态(联机->脱机),但代码中似乎没有async调用,因此我认为它只执行一次,然后数据集不会被更改。

我该如何解决我的问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-14 16:17:07

PubNub存在

您可以使用PubNub存在监视联机和状态更改。当您订阅时,在启用存在的情况下订阅,您将得到state-changejoinleave & timeout 回调

代码语言:javascript
运行
复制
Callback callback = new Callback() {
    @Override
    public void successCallback(String channel, Object message) {
        System.out.println(channel + " : "
                + message.getClass() + " : " + message.toString());

       // take action on the presence events here
    }
 
    @Override
    public void connectCallback(String channel, Object message) {
       System.out.println("CONNECT on channel:" + channel
                + " : " + message.getClass() + " : "
                + message.toString());
    }
 
    @Override
    public void disconnectCallback(String channel, Object message) {
        System.out.println("DISCONNECT on channel:" + channel
                + " : " + message.getClass() + " : "
                + message.toString());
    }
 
    @Override
    public void reconnectCallback(String channel, Object message) {
        System.out.println("RECONNECT on channel:" + channel
                + " : " + message.getClass() + " : "
                + message.toString());
    }
 
    @Override
    public void errorCallback(String channel, PubnubError error) {
        System.out.println("ERROR on channel " + channel
                + " : " + error.toString());
    }
};
 
try {
    pubnub.presence("my_channel", callback);
} 
catch (PubnubException e) {
    System.out.println(e.toString());
}

现在看来,Sinch正在使用PubNub Android的一个相当老的版本。我认为您仍然可以使用PubNub Android v4在Sinch之外执行您需要做的事情,除非Sinch需要使用相同版本的SDK。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39474613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档