How to receive missed messages on resuming connection lost in pubnub?

一笑奈何 提交于 2019-12-06 16:14:56

As per PubNub sample chat, you need to implement code to get the last n messages(n: number of messages preferred).

/**
 * Get last 100 messages sent on current channel from history.
 */
public void history() {
    this.mPubNub.history(this.channel, 100, false, new Callback() {
        @Override
        public void successCallback(String channel, final Object message) {
            try {
                JSONArray json = (JSONArray) message;
                Log.d("History", json.toString());
                final JSONArray messages = json.getJSONArray(0);
                final List<ChatMessage> chatMsgs = new ArrayList<ChatMessage>();
                for (int i = 0; i < messages.length(); i++) {
                    try {
                        if (!messages.getJSONObject(i).has("data"))
                            continue;
                        JSONObject jsonMsg = messages.getJSONObject(i)
                                .getJSONObject("data");
                        String name = jsonMsg
                                .getString(Constants.JSON_USER);
                        String msg = jsonMsg.getString(Constants.JSON_MSG);
                        long time = jsonMsg.getLong(Constants.JSON_TIME);
                        ChatMessage chatMsg = new ChatMessage(name, msg,
                                time);
                        chatMsgs.add(chatMsg);
                    } catch (JSONException e) { // Handle errors silently
                        e.printStackTrace();
                    }
                }

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "RUNNIN",
                                Toast.LENGTH_SHORT).show();
                        mChatAdapter.setMessages(chatMsgs);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void errorCallback(String channel, PubnubError error) {
            Log.d("History", error.toString());
        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!