Publish/Subscribe API for PubNub Android SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
Description
The publish()
function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey
at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
Publish Anytime
It's not required to be subscribed to a channel in order to publish to that channel.
Message Data
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data
should not contain special Android V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Don't JSON serialize
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
Message Size
The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
For further details, check Calculating Message Payload Size Before Publish.
Message Publish Rate
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably
There are some best practices to ensure messages are delivered when publishing to a channel:
Publish to any given channel in a serial manner (not concurrently).
Check that the return code is success (for example,
[1,"Sent","136074940..."]
)Publish the next message only after receiving a success return code.
If a failure code is returned (
[0,"blah","<timetoken>"]
), retry the publish.Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
Throttle publish bursts in accordance with your app's latency needs, for example, Publish no faster than 5 msgs per second to any one channel.
Method(s)
To Publish a message
you can use the following method(s) in the Android V4 SDK:
this.pubnub.publish()
.message(Object)
.channel(String)
.shouldStore(Boolean)
.meta(Object)
.queryParam(HashMap)
.usePOST(Boolean)
.ttl(Integer);
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object | Yes | The payload. | |
channel | String | Yes | Destination of the message . | |
shouldStore | Boolean | Optional | account default | Store in history. If shouldStore is not specified, then the history configuration on the key is used. |
meta | Object | Optional | Not set | Meta data object which can be used with the filtering ability. |
queryParam | HashMap<string,string> | Optional | Not set | One or more query parameters to be passed to the server, for analytics purposes. Overridden in case of conflicts with reserved PubNub parameters, such as uuid or instance_id . Accessible from your PubNub Dashboard, and never returned in server responses. |
usePOST | Boolean | Optional | false | Use POST to publish . |
ttl | Integer | Optional | Set a per message time to live in Message Persistence.
| |
sync | Command | Optional | Block the thread, exception thrown if something goes wrong. | |
async | PNCallback | Optional | PNCallback of type PNPublishResult |
Basic Usage
Publish a message to a channel
JsonObject position = new JsonObject();
position.addProperty("lat", 32L);
position.addProperty("lng", 32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position)
.channel("my_channel")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
// handle publish result, status always present, result if successful
// status.isError() to see if error happened
if(!status.isError()) {
System.out.println("pub timetoken: " + result.getTimetoken());
show all 19 linesSubscribe to the channel
Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
Returns
The publish()
operation returns a PNPublishResult
which contains the following operations:
Method | Type | Description |
---|---|---|
getTimetoken() | Long | Returns a long representation of the timetoken when the message was published. |
Other Examples
Publish with metadata
pubnub.publish()
.message(Arrays.asList("hello", "there"))
.channel("suchChannel")
.shouldStore(true)
.meta(<Object>) // optional meta data object which can be used with the filtering ability.
.usePOST(true)
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
// handle publish result, status always present, result if successful
// status.isError to see if error happened
}
});
Publishing JsonObject (Google GSON)
JsonObject position = new JsonObject();
position.addProperty("lat", 32L);
position.addProperty("lng", 32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position)
.channel("my_channel")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
// handle publish result, status always present, result if successful
// status.isError() to see if error happened
if(!status.isError()) {
System.out.println("pub timetoken: " + result.getTimetoken());
show all 19 linesPublishing JsonArray (Google GSON)
JsonArray position = new JsonArray();
position.add(32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(position)
.channel("my_channel")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
// handle publish result, status always present, result if successful
// status.isError to see if error happened
if(!status.isError()) {
System.out.println("pub timetoken: " + result.getTimetoken());
}
show all 18 linesPublishing JSONObject (org.json)
JSONObject position = new JSONObject();
position.put("lat", 32L);
position.put("lng", 32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(toMap(position))
.channel("my_channel")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
// handle publish result, status always present, result if successful
// status.isError to see if error happened
if(!status.isError()) {
System.out.println("pub timetoken: " + result.getTimetoken());
show all 19 linesHelper Functions
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
show all 35 linesPublishing JSONArray (org.json)
JSONArray position = new JSONArray();
position.put(32L);
System.out.println("before pub: " + position);
pubnub.publish()
.message(toList(position))
.channel("my_channel")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
// handle publish result, status always present, result if successful
// status.isError to see if error happened
if(!status.isError()) {
System.out.println("pub timetoken: " + result.getTimetoken());
}
show all 18 linesHelper Functions
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
Store the published message for 10 hours
PNPublishResult result = pubnub.publish()
.channel("coolChannel")
.message("test")
.shouldStore(true)
.ttl(10)
.sync();
Fire
Description
The fire endpoint allows the client to send a message to Functions Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire()
isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the Android V4 SDK:
this.pubnub.fire()
.message(Object)
.channel(String)
.meta(Object)
.usePOST(Boolean);
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
message | Object | Yes | The payload. | |
channel | String | Yes | Destination of the message . | |
meta | Object | Optional | Not set | Meta data object which can be used with the filtering ability. |
usePOST | Boolean | Optional | false | Use POST to publish . |
sync | Command | Optional | Block the thread, exception thrown if something goes wrong. | |
async | PNCallback | Optional | PNCallback of type PNPublishResult |
Basic Usage
Fire a message to a channel
pubnub.fire()
.message(Arrays.asList("hello", "there"))
.channel("my_channel")
.usePOST(true)
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
if (status.isError()) {
// something bad happened.
System.out.println("error happened while publishing: " + status.toString());
} else {
System.out.println("publish worked! timetoken: " + result.getTimetoken());
}
}
});
Signal
Description
The signal()
function is used to send a signal to all subscribers of a channel.
By default, signals are limited to a message payload size of 64
bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.
Method(s)
To Signal a message
you can use the following method(s) in the Android V4 SDK:
this.pubnub.signal()
.message(Object)
.channel(String);
Parameter | Type | Required | Description |
---|---|---|---|
message | Object | Yes | The payload which will be serialized and sent. |
channel | String | Yes | The channel which the signal will be sent to. |
sync | PNPublishResult | Optional | Executes the call. Blocks the thread, exception is thrown if something goes wrong. |
async | PNCallback<PNPublishResult> | Optional | Executes the call asynchronously. |
Basic Usage
Signal a message to a channel
pubnub.signal()
.message("Hello everyone!")
.channel("bar")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
if (pnStatus.isError()) {
Long timetoken = pnPublishResult.getTimetoken(); // signal message timetoken
} else {
pnStatus.getErrorData().getThrowable().printStackTrace();
}
}
});
Response
The signal()
operation returns a PNPublishResult
object which contains the following operations:
Method | Type | Description |
---|---|---|
getTimetoken() | Long | Returns a long representation of the timetoken when the signal was published. |
Subscribe
Description
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel
. To subscribe to a channel
the client must send the appropriate subscribeKey
at initialization.
By default a newly subscribed client will only receive messages published to the channel after the subscribe()
call completes.
If a client gets disconnected from a channel, it can automatically attempt to reconnect to that channel
and retrieve any available messages that were missed during that period. This can be achieved by setting setReconnectionPolicy
to PNReconnectionPolicy.LINEAR
, when initializing the client.
Unsubscribing from all channels
Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken
and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Subscribe to a channel
you can use the following method(s) in the Android V4 SDK:
pubnub.subscribe()
.channels(Array)
.channelGroups(Arrays)
.withTimetoken(Long)
.withPresence()
.execute();
Parameter | Type | Required | Description |
---|---|---|---|
channels | Array | Optional | Subscribe to channels , Either channel or channelGroup is required |
channelGroups | Array | Optional | Subscribe to channel groups , Either channel or channelGroup is required |
withTimetoken | Long | Optional | Pass a timetoken |
withPresence() | Command | Optional | Also subscribe to related presence information |
execute() | Command | Yes | Command that will execute subscribe . |
Basic Usage
Subscribe to a channel:
pubnub.subscribe()
.channels(Arrays.asList("my_channel")) // subscribe to channels
.execute();
Event listeners
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Returns
PNMessageResult
PNMessageResult
PNMessageResult
is returned in the Listeners.
The subscribe()
operation returns a PNStatus
which contains the following operations:
Method | Type | Description |
---|---|---|
getCategory() | Enum of type PNStatusCategory . | Details of PNStatusCategory are here |
isError() | Boolean | Is true in case of an error. |
The subscribe()
operation returns a PNMessageResult
for messages which contains the following operations:
Method | Type | Description |
---|---|---|
getMessage() | JsonElement | The message sent on the channel . |
getSubscription() | String | The channel group or wildcard subscription match (if exists). |
getChannel() | String | The channel for which the message belongs. |
getTimetoken() | Long | Timetoken for the message. |
getUserMetadata() | Object | User metadata . |
The subscribe()
operation returns a PNPresenceEventResult
from presence which contains the following operations:
Method | Type | Description |
---|---|---|
getEvent() | String | Events like join , leave , timeout , state-change , interval . |
getUuid() | String | UUID for the event. |
getTimestamp() | Long | Timestamp for the event. |
getOccupancy() | Int | Current occupancy . |
getState() | JsonElement | State of the UUID . |
getSubscription() | String | The channel group or wildcard subscription match (if exists). |
getChannel() | String | The channel for which the message belongs. |
getTimetoken() | Long | Timetoken of the message. |
getUserMetadata() | Object | User metadata . |
The subscribe()
operation returns a PNSignalResult
for signals which contains the following operations:
Method | Type | Description |
---|---|---|
getMessage() | JsonElement | The signal sent on the channel . |
getSubscription() | String | The channel group or wildcard subscription match (if exists). |
getChannel() | String | The channel for which the signal belongs. |
getTimetoken() | Long | Timetoken for the signal. |
getUserMetadata() | Object | User metadata . |
Other Examples
Basic subscribe with logging
PNConfiguration pnConfiguration = new PNConfiguration();
// subscribeKey from admin panel
pnConfiguration.setSubscribeKey("my_subkey"); // required
// publishKey from admin panel (only required if publishing)
pnConfiguration.setPublishKey("my_pubkey");
pnConfiguration.setLogVerbosity(PNLogVerbosity.BODY);
PubNub pubnub = new PubNub(pnConfiguration);
pubnub.subscribe()
.channels(Arrays.asList("my_channel")) // subscribe to channels information
.execute();
Subscribing to multiple channels
It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.
Alternative subscription methods
You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.
pubnub.subscribe()
.channels(Arrays.asList("my_channel1","my_channel2" )) // subscribe to channels information
.execute();
Subscribing to a Presence channel
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres
to the channel name. For example the channel named my_channel
would have the presence channel named my_channel-pnpres
. Presence data can be observed inside the SubscribeCallback#message(PubNub, PNMessageResult)
callback.
pubnub.subscribe()
.channels(Arrays.asList("my_channel")) // subscribe to channels
.withPresence() // also subscribe to related presence information
.execute();
Sample Responses
Join Event
if (presence.getEvent().equals("join")) {
presence.getUuid(); // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.getTimestamp(); // 1345546797
presence.getOccupancy(); // 2
}
Leave Event
if (presence.getEvent().equals("leave")) {
presence.getUuid(); // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.getTimestamp(); // 1345546797
presence.getOccupancy(); // 2
}
Timeout Event
if (presence.getEvent().equals("timeout")) {
presence.getUuid(); // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.getTimestamp(); // 1345546797
presence.getOccupancy(); // 2
}
Custom Presence Event (State Change)
{
"action": "state-change",
"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
"timestamp": 1345549797,
"data": {
"isTyping": true
}
}
Interval Event
if (presence.getEvent().equals("interval")) {
presence.getUuid(); // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
presence.getTimestamp(); // 1345546797
presence.getOccupancy(); // 2
}
When a channel is in interval mode with presence_deltas
pnconfig
flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message. This settings can be altered in the Admin Portal
- joined
- left
- timedout
For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:
if (presence.getEvent().equals("interval")) {
presence.getTimestamp(); // <unix timestamp>
presence.getOccupancy(); // <# users in channel>
presence.getJoin(); // ["uuid1", "uuid2"]
presence.getTimeout(); // ["uuid3"]
}
If the full interval message is greater than 30KB
(since the max publish payload is ∼32KB
), none of the extra fields will be present. Instead there will be a here_now_refresh
boolean field set to true
. This indicates to the user that they should do a hereNow
request to get the complete list of users present in the channel.
if (presence.getEvent().equals("interval")) {
presence.getTimestamp(); // <unix timestamp>
presence.getOccupancy(); // <# users in channel>
presence.getHereNowRefresh() // true
}
Wildcard subscribe to channels
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.
Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.*
you will get all messages for a.b
, a.c
, a.x
. The wildcarded *
portion refers to any portion of the channel string name after the dot (.)
.
pubnub.subscribe()
.channels(Arrays.asList("foo.*")) // subscribe to channels information
.execute();
Wildcard grants and revokes
Only one level (a.*
) of wildcarding is supported. If you grant on *
or a.b.*
, the grant will treat *
or a.b.*
as a single channel named either *
or a.b.*
. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*
.
Subscribing with State
Requires Presence add-on
This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Required UUID
UUID
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.setSubscribeKey("demo");
pnConfiguration.setPublishKey("demo");
class complexData {
String fieldA;
int fieldB;
}
PubNub pubnub= new PubNub(pnConfiguration);
pubnub.addListener(new SubscribeCallback() {
@Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getCategory() == PNStatusCategory.PNConnectedCategory){
show all 42 linesSubscribe to a channel group
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.subscribe()
.channels(Arrays.asList("ch1", "ch2")) // subscribe to channels
.channelGroups(Arrays.asList("cg1", "cg2")) // subscribe to channel groups
.withTimetoken(1337L) // optional, pass a timetoken
.withPresence() // also subscribe to related presence information
.execute();
Subscribe to the presence channel of a channel group
Requires Stream Controller and Presence add-ons
This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.subscribe()
.channelGroups(Arrays.asList("cg1", "cg2")) // subscribe to channel groups
.withTimetoken(1337L) // optional, pass a timetoken
.withPresence() // also subscribe to related presence information
.execute();
Unsubscribe
Description
When subscribed to a single channel, this function causes the client to issue a leave
from the channel
and close any open socket to the PubNub Network. For multiplexed channels, the specified channel
(s) will be removed and the socket remains open until there are no more channels remaining in the list.
Unsubscribing from all channels
Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken
and thus, there could be some gaps in the subscription that may lead to message loss.
Method(s)
To Unsubscribe from a channel
you can use the following method(s) in the Android V4 SDK:
pubnub.unsubscribe()
.channels(Array)
.channelGroups(Array)
.execute();
Parameter | Type | Required | Description |
---|---|---|---|
channels | Array | Optional | Unsubscribe to channels , Either channel or channelGroup is required |
channelGroups | Array | Optional | Unsubscribe to channel groups, Either channel or channelGroup is required |
execute() | Command | Yes | Command that will execute unsubscribe . |
Basic Usage
Unsubscribe from a channel:
pubnub.unsubscribe()
.channels(Arrays.asList("my_channel"))
.execute();
Event listeners
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
Response
The output below demonstrates the response to a successful call:
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
if (presence.getEvent().equals("leave")) {
presence.getTimestamp(); // 1345546797
presence.getOccupancy(); // 2
presence.getUuid(); // left_uuid
}
}
Other Examples
Unsubscribing from multiple channels
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
pubnub.unsubscribe()
.channels(Arrays.asList("ch1", "ch2", "ch3"))
.channelGroups(Arrays.asList("cg1", "cg2", "cg3"))
.execute();
Example Response
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
if (presence.getEvent().equals("leave")) {
presence.getTimestamp(); // 1345546797
presence.getOccupancy(); // 2
presence.getUuid(); // left_uuid
}
}
Unsubscribe from a channel group
pubnub.unsubscribe()
.channelGroups(Arrays.asList("cg1", "cg2", "cg3"))
.execute();
Example Response
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
if (presence.getEvent().equals("leave")) {
presence.getTimestamp(); // 1345546797
presence.getOccupancy(); // 2
presence.getUuid(); // left_uuid
}
}
Unsubscribe All
Description
Unsubscribe from all channels and all channel groups
Method(s)
public final void unsubscribeAll()
Basic Usage
pubnub.unsubscribeAll();
Returns
None
Listeners
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Adding Listeners
pubnub.addListener(new SubscribeCallback() {
// PubNub status
@Override
public void status(PubNub pubnub, PNStatus status) {
switch (status.getOperation()) {
// combine unsubscribe and subscribe handling for ease of use
case PNSubscribeOperation:
case PNUnsubscribeOperation:
// Note: subscribe statuses never have traditional errors,
// just categories to represent different issues or successes
// that occur as part of subscribe
switch (status.getCategory()) {
case PNConnectedCategory:
// No error or issue whatsoever.
case PNReconnectedCategory:
show all 129 linesRemoving Listeners
SubscribeCallback subscribeCallback = new SubscribeCallback() {
@Override
public void status(PubNub pubnub, PNStatus status) {
}
@Override
public void message(PubNub pubnub, PNMessageResult message) {
}
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
show all 52 linesHandling Disconnects
SubscribeCallback subscribeCallback = new SubscribeCallback() {
@Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
// internet got lost, do some magic and call reconnect when ready
pubnub.reconnect();
} else if (status.getCategory() == PNStatusCategory.PNTimeoutCategory) {
// do some magic and call reconnect when ready
pubnub.reconnect();
} else {
log.error(status);
}
}
@Override
show all 26 linesListener status events
Category | Description |
---|---|
PNNetworkUpCategory | The SDK detected that the network is online. |
PNNetworkDownCategory | The SDK announces this when a connection isn't available, or when the SDK isn't able to reach the PubNub Data Stream Network. |
PNNetworkIssuesCategory | A subscribe event experienced an exception when running. The SDK isn't able to reach the PubNub Data Stream Network. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNConnectedCategory | SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes. |
PNAccessDeniedCategory | Access Manager permission failure. |
PNMalformedResponseCategory | JSON parsing crashed. |
PNBadRequestCategory | The server responded with a bad response error because the request is malformed. |
PNDecryptionErrorCategory | If using decryption strategies and the decryption fails. |
PNTimeoutCategory | Failure to establish a connection to PubNub due to a timeout. |
PNRequestMessageCountExceedCategory | The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
PNUnknownCategory | Returned when the subscriber gets a non-200 HTTP response code from the server. |