AndroidAndroid V4 Storage & Playback API Reference for Realtime Apps

Go to Channel Groups


Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order, for example you can:
  • Search for messages starting on the newest end of the timeline (default behavior - reverse = false)
  • Search for messages from the oldest end of the timeline by setting reverse to true.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the count parameter.
 
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
To run History you can use the following method(s) in the Android V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    channelStringYesSpecifies channelto return history messages from.
    reverseBooleanOptionalfalseSetting to true will traverse the time line in reverse starting with the oldest message first.
    includeTimetokenBooleanOptionalfalseWhether event dates time tokens should be included in response or not.
    startLongOptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    endLongOptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    countIntOptional100Specifies the number of historical messages to return.
    asyncPNCallbackYesPNCallback of type PNHistoryResult.
Retrieve the last 100 messages on a channel:
pubnub.history()
	.channel("history_channel") // where to fetch history from
	.count(100) // how many items to fetch
	.async(new PNCallback<PNHistoryResult>() {
		@Override
		public void onResponse(PNHistoryResult result, PNStatus status) {
 
		}
	});
The history() operation returns a PNHistoryResult which contains the following operations:
MethodTypeDescription
getMessages()List<PNHistoryItemResult>List of messages of type PNHistoryItemResult. See PNHistoryItemResult for more details.
getStartTimetoken()LongStart timetoken.
getEndTimetoken()LongEnd timetoken.
MethodTypeDescription
getTimetoken()LongTimetoken of the message.
getEntry()JsonElementMessage.
  1. pubnub.history()
        .channel("my_channel") // where to fetch history from
        .count(3) // how many items to fetch
        .reverse(true) // should go in reverse?
        .async(new PNCallback<PNHistoryResult>() {
            @Override
            public void onResponse(PNHistoryResult result, PNStatus status) {
    
            }
        });
    if (!status.isError()) {
        for (PNHistoryItemResult pnHistoryItemResult: result.getMessages()) {
            pnHistoryItemResult.getEntry(); // custom JSON structure for message
        }
    }
  2. pubnub.history()
    	.channel("my_channel") // where to fetch history from
    	.start(13847168620721752L) // first timestamp
    	.reverse(true) // should go in reverse?
    	.async(new PNCallback<PNHistoryResult>() {
    		@Override
    		public void onResponse(PNHistoryResult result, PNStatus status) {
    		
    		}
    	});
    if (!status.isError()) {
        for (PNHistoryItemResult pnHistoryItemResult: result.getMessages()) {
            pnHistoryItemResult.getEntry(); // custom JSON structure for message
        }
    }
  3. pubnub.history()
        .channel("my_channel") // where to fetch history from
        .count(100) // how many items to fetch
        .start(-1) // first timestamp 
        .end(13847168819178600L) // last timestamp
        .reverse(true) // should go in reverse?
        .async(new PNCallback<PNHistoryResult>() {
            @Override
            public void onResponse(PNHistoryResult result, PNStatus status) {
    
            }
        });
    [
    	["Pub3","Pub4","Pub5"],
    	13406746780720711,
    	13406746845892666
    ]
    
  4.  
    Usage!
    You can call the method by passing 0 or a valid time token as the argument.
    package com.pubnub.api;
    
    import com.pubnub.api.PNConfiguration;
    import com.pubnub.api.PubNub;
    import com.pubnub.api.callbacks.PNCallback;
    import com.pubnub.api.models.consumer.PNStatus;
    import com.pubnub.api.models.consumer.history.PNHistoryItemResult;
    import com.pubnub.api.models.consumer.history.PNHistoryResult;
    
    public class PubNubRecursiveHistoryFetcher {
    
        private PubNub pubnub;
    
        private static abstract class CallbackSkeleton {
            public abstract void handleResponse(PNHistoryResult result);
        }
    
        private PubNubRecursiveHistoryFetcher() {
            // NOTICE: for demo/demo pub/sub keys Storage & Playback is disabled,
            // so use your pub/sub keys instead
            PNConfiguration pnConfiguration = new PNConfiguration();
            pnConfiguration.setSubscribeKey("demo");
            pubnub = new PubNub(pnConfiguration);
        }
    
        public static void main(String[] args) {
            PubNubRecursiveHistoryFetcher fetcher = new PubNubRecursiveHistoryFetcher();
            fetcher.getAllMessages("my_channel", null, 10, new CallbackSkeleton() {
                @Override
                public void handleResponse(PNHistoryResult result) {
                    for (PNHistoryItemResult message : result.getMessages()) {
                        System.out.println(message.getEntry());
                    }
                }
            });
        }
    
        /**
         * Fetches channel history in a recursive manner, in chunks of specified size, starting from the most recent,
         * with every subset (with predefined size) sorted by the timestamp the messages were published.
         *
         * @param channel  The channel where to fetch history from
         * @param start    The timetoken which the fetching starts from
         * @param count    Chunk size
         * @param callback Callback which fires when a chunk is fetched
         */
        private void getAllMessages(final String channel, Long start, final int count, final CallbackSkeleton callback) {
            pubnub.history()
                    .channel(channel)
                    .count(count)
                    .start(start)
                    .includeTimetoken(true)
                    .async(new PNCallback<PNHistoryResult>() {
                        @Override
                        public void onResponse(PNHistoryResult result, PNStatus status) {
                            if (!status.isError() && !result.getMessages().isEmpty()) {
                                callback.handleResponse(result);
                                getAllMessages(channel, result.getMessages().get(0).getTimetoken(), count, callback);
                            }
                        }
                    });
        }
    }
    
  5. pubnub.history()
    	.channel("history_channel") // where to fetch history from
    	.count(100) // how many items to fetch
    	.includeTimetoken(true) // include timetoken with each entry
    	.async(new PNCallback<PNHistoryResult>() {
    		@Override
    		public void onResponse(PNHistoryResult result, PNStatus status) {
     
    		}
    	});
Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
This function fetches historical messages of a channel.
PubNub Storage/Playback Service provides real-time access to an unlimited history for all messages published to PubNub. Stored messages are replicated across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption ensuring that they are not readable while stored on PubNub's network.
It is possible to control how messages are returned and in what order, for example you can:
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Limit the number of messages to a specific quantity using the maximumPerChannel parameter.
Start & End parameter usage clarity:
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value.
If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer.
Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value).
Keep in mind that you will still receive a maximum of 25 messages per channel even if there are more messages that meet the timetoken values.
To run Batch History you can use the following method(s) in the Android V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    channelsArrayYesSpecifies channelsto return history messages from.
    startLongOptionalTime token delimiting the start of time slice (exclusive) to pull messages from.
    endLongOptionalTime token delimiting the end of time slice (inclusive) to pull messages from.
    maximumPerChannelIntOptional25Specifies the number of historical messages to return per channel.

    Default/Maximum is 25 per channel.
    asyncPNCallbackYesPNCallback of type PNHistoryResult.
Retrieve the last 25 messages on a channel:
// assuming pubnub is an initialized instance
pubnub.fetchMessages()
    .channels(Arrays.asList("ch1", "ch2", "ch3"))
    .start(123)
    .end(1234)
    .maximumPerChannel(25)
    .async(new PNCallback<PNFetchMessagesResult>() {
        @Override
        public void onResponse(PNFetchMessagesResult result, PNStatus status) {
            // handle resposne here
        }
    });
 
The batch history is limited to 500 channels and only the last 25 messages per channel.

The response is of the type Map.

KeyValue
channel names

List of PNMessageResult as shown here:

http://www.pubnub.com/docs/android-java/api-reference-publish-and-subscribe#subscribe_returns

  1. package com.we.pubnubtest.utils;
    
    import com.pubnub.api.models.consumer.history.PNFetchMessagesResult;
    
    /**
     * Created by tukunare on 2/8/2017.
     */
    public abstract class CallbackSkeleton {
    
        public CallbackSkeleton() {
        }
    
        public abstract void handleResponse(PNFetchMessagesResult result);
    
        public abstract void finish();
    
    }
    package com.we.pubnubtest.utils;
    
    import com.pubnub.api.PubNub;
    import com.pubnub.api.callbacks.PNCallback;
    import com.pubnub.api.models.consumer.PNStatus;
    import com.pubnub.api.models.consumer.history.PNFetchMessagesResult;
    import com.pubnub.api.models.consumer.pubsub.PNMessageResult;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.concurrent.CountDownLatch;
    
    /**
     * Created by tukunare on 2/8/2017.
     */
    public class PubnubRecursiveHistoryFetcher {
        private PubNub pubNub;
        private String channels;
    
    
        public PubnubRecursiveHistoryFetcher(PubNub pubNub, String channels) {
            this.pubNub = pubNub;
            this.channels = channels;
        }
    
        public void getAllMessages(CallbackSkeleton callback) {
            getAllMessages(null, callback);
        }
    
        public void getAllMessages(Long startTimestamp, final CallbackSkeleton callback) {
            final CountDownLatch latch = new CountDownLatch(1);
            final Long timeToken;
    
            if (startTimestamp == null) {
                startTimestamp = -1L;
            }
    
            timeToken = startTimestamp;
    
            pubNub.fetchMessages()
                .channels(Arrays.asList(channels)) // where to fetch history from
                .start(startTimestamp) // first timestamp
                .maximumPerChannel(25)
                .async(new PNCallback<PNFetchMessagesResult>() {
                    @Override
                    public void onResponse(PNFetchMessagesResult result, PNStatus status) {
                        // handle resposne here
                        if (!status.isError() && result.getChannels().size()!=0) {
    
                            callback.handleResponse(result);
    
                            Long timetoken = timeToken;
    
                            for (List<PNMessageResult> itens: result.getChannels().values()) {
    
                                for (PNMessageResult item: itens) {
                                    if (item.getTimetoken()<timetoken) {
                                        timetoken = item.getTimetoken();
                                    }
                                }
                            }
    
                            getAllMessages(timetoken, callback);
                        } else {
                            callback.finish();
                        }
                    }
                });
        }
    }
Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
Removes the messages from the history of a specific channel.
 
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Administration Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the Android V4 SDK.
  1. ParameterTypeRequiredDefaultsDescription
    channelsArrayYesSpecifies channels to delete messages from.
    startLongOptionalTime token delimiting the start of time slice (inclusive) to delete messages from.
    endLongOptionalTime token delimiting the end of time slice (exclusive) to delete messages from.
    asyncPNCallbackYesPNCallback of type PNDeleteMessagesResult.
pubnub.deleteMessages()
    .channels(Arrays.asList("channel_1", "channel_2"))
    .start(1460693607379L)
    .end(1460893617271L)
    .async(new PNCallback<PNDeleteMessagesResult>() {
        @Override
        public void onResponse(PNDeleteMessagesResult result, PNStatus status) {
            // The deleteMessages() method does not return actionable data, be sure to check the status
            // object on the outcome of the operation by checking the status.isError().
        }
    });

  1. To delete a specific message, pass the publish timetoken (received from a successful publish) in the End parameter and timetoken +/- 1 in the Start parameter. e.g. if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.
    pubnub.deleteMessages()
        .channels(Arrays.asList("channel_1"))
        .start(15526611838554309L)
        .end(15526611838554310L)
        .async(new PNCallback<PNDeleteMessagesResult>() {
            @Override
            public void onResponse(PNDeleteMessagesResult result, PNStatus status) {
                // The deleteMessages() method does not return actionable data, be sure to check the status
                // object on the outcome of the operation by checking the status.isError().
            }
        });
Requires Storage & Playback add-on XRequires that the Storage & Playback add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
Returns the number of messages published on one or more channels since a given time. The count returned is the number of messages in history with a timetoken value greater than the passed value in the channelsTimetokenparameter.
 For keys with unlimited message retention enabled, this method considers only messages published in the last 7 days.
You can use the following method(s) in the Android V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channels ArrayYesThe channels to fetch the message count
    channelsTimetoken ArrayYesList of timetokens, in order of the channels list. Specify a single timetoken to apply it to all channels. Otherwise, the list of timetokens must be the same length as the list of channels, or the function returns a PNStatuswith an error flag.
    asyncPNCallbackYesPNCallback of type PNMessageCountResult.
Long lastHourTimetoken = (Calendar.getInstance().getTimeInMillis() - TimeUnit.HOURS.toMillis(1)) * 10000L;

pubnub.messageCounts()
    .channels(Arrays.asList("news"))
    .channelsTimetoken(Arrays.asList(lastHourTimetoken))
    .async(new PNCallback<PNMessageCountResult>() {
        @Override
        public void onResponse(PNMessageCountResult result, PNStatus status) {
            if (!status.isError()) {
                for (Map.Entry<String, Long> messageCountEntry : result.getChannels().entrySet()) {
                    messageCountEntry.getKey(); // the channel name
                    messageCountEntry.getValue(); // number of messages for that channel
                }
            } else {
                // Handle error accordingly.
                status.getErrorData().getThrowable().printStackTrace();
            }
        }
    });
The operation returns a PNMessageCountResult which contains the following operations
MethodTypeDescription
getChannels()Map<String, Long>A map with values of Long for each channel. Channels without messages have a count of 0. Channels with 10,000 messages or more have a count of 10000.
  1. Long lastHourTimetoken = (Calendar.getInstance().getTimeInMillis() - TimeUnit.HOURS.toMillis(1)) * 10000L;
    Long lastDayTimetoken = (Calendar.getInstance().getTimeInMillis() - TimeUnit.DAYS.toMillis(1)) * 10000L;
    
    pubnub.messageCounts()
        .channels(Arrays.asList("news", "info"))
        .channelsTimetoken(Arrays.asList(lastHourTimetoken, lastDayTimetoken))
        .async(new PNCallback<PNMessageCountResult>() {
            @Override
            public void onResponse(PNMessageCountResult result, PNStatus status) {
                if (!status.isError()) {
                    for (Map.Entry<String, Long> messageCountEntry : result.getChannels().entrySet()) {
                        messageCountEntry.getKey(); // the channel name
                        messageCountEntry.getValue(); // number of messages for that channel
                    }
                } else {
                    // Handle error accordingly.
                    status.getErrorData().getThrowable().printStackTrace();
                }
            }
        });

Go to Mobile Push