AndroidAndroid V4 Publish & Subscribe API Reference for Realtime Apps

Go to Configuration


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 is 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. Message 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.
Message Size:
The maximum number of characters per message is 32K 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.5KB) 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 please check: https://support.pubnub.com/support/discussions/topics/14000006322

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 cannot 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 (i.e. not concurrently).
  • Check that the return code is success (e.g. [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 e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not 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.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the Android V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    messageObjectYesThe payload.
    channelStringYesDestination of the message.
    shouldStoreBooleanOptionalaccount default

    Store in history.

    If shouldStore is not specified, then the history configuration on the key is used.

    metaObjectOptionalNot setMeta data object which can be used with the filtering ability.
    usePOSTBooleanOptional falseUse POST to publish.
    ttlIntegerOptional
    Set a per message time to live in storage.
    1. If shouldStore = true, and ttl = 0, the message is stored with no expiry time.
    2. If shouldStore = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
    3. If shouldStore = false, the ttl parameter is ignored.
    4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
    syncCommandOptionalBlock the thread, exception thrown if something goes wrong.
    asyncPNCallbackOptionalPNCallback of type PNPublishResult

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());
            }
            System.out.println("pub status code: " + status.getStatusCode());
        }
    });
 
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.
The publish() operation returns a PNPublishResult which contains the following operations:
MethodTypeDescription
getTimetoken()LongReturns a long representation of the time token when the message was published.
  1. 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
            }
        });
  2. 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());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
  3. 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());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
  4. 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());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
    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);
            }
            map.put(key, value);
        }
        return map;
    }
    
    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;
    }
  5. 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());
                }
                System.out.println("pub status code: " + status.getStatusCode());
            }
        });
    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;
    }
  6. PNPublishResult result = pubnub.publish()
                                 .channel("coolChannel")
                                 .message("test")
                                 .shouldStore(true)
                                 .ttl(10)
                                 .sync();
The fire endpoint allows the client to send a message to PubNub 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() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the Android V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    messageObjectYesThe payload.
    channelStringYesDestination of the message.
    metaObjectOptionalNot setMeta data object which can be used with the filtering ability.
    usePOSTBooleanOptional falseUse POST to publish.
    syncCommandOptionalBlock the thread, exception thrown if something goes wrong.
    asyncPNCallbackOptionalPNCallback of type PNPublishResult

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

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 30 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.

To Signal a message you can use the following method(s) in the Android V4 SDK:
  1. ParameterTypeRequiredDescription
    messageObjectYesThe payload which will be serialized and sent.
    channelStringYesThe channel which the signal will be sent to.
    syncPNPublishResultOptionalExecutes the call. Blocks the thread, exception is thrown if something goes wrong.
    asyncPNCallback<PNPublishResult>OptionalExecutes the call asynchronously.

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();
            }
        }
    });
The signal() operation returns a PNPublishResult object which contains the following operations:
MethodTypeDescription
getTimetoken()LongReturns a long representation of the time token when the signal was published.
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 the channel(s) 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 the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the Android V4 SDK:
  1. ParameterTypeRequiredDescription
    channelsArrayOptionalSubscribe to channels, Either channel or channelGroup is required
    channelGroupsArrayOptionalSubscribe to channel groups, Either channel or channelGroup is required
    withTimetokenLongOptionalPass a timetoken
    withPresence()CommandOptionalAlso subscribe to related presence information
    execute()CommandYesCommand that will execute subscribe.
Subscribe to a channel:
pubnub.subscribe()
    .channels(Arrays.asList("my_channel")) // subscribe to channels
    .execute();
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.
 

PNMessageResult is returned in the Listeners.

The subscribe() operation returns a PNStatus which contains the following operations:
MethodTypeDescription
getCategory()Enum of type PNStatusCategory.Details of PNStatusCategory are here.
isError()BooleanIs true in case of an error.
The subscribe() operation returns a PNMessageResult for messages which contains the following operations:
MethodTypeDescription
getMessage()JsonElementThe message sent on the channel.
getSubscription()StringThe channel group or wildcard subscription match (if exists).
getChannel()StringThe channel for which the message belongs.
getTimetoken()LongTimetoken for the message.
getUserMetadata()ObjectUser metadata.
The subscribe() operation returns a PNPresenceEventResult from presence which contains the following operations:
MethodTypeDescription
getEvent()StringEvents like join, leave, timeout, state-change, interval.
getUuid()StringUUID for the event.
getTimestamp()LongTimestamp for the event.
getOccupancy()IntCurrent occupancy.
getState()JsonElementState of the UUID.
getSubscription()StringThe channel group or wildcard subscription match (if exists).
getChannel()StringThe channel for which the message belongs.
getTimetoken()LongTimetoken of the message.
getUserMetadata()ObjectUser metadata.
The subscribe() operation returns a PNSignalResult for signals which contains the following operations:
MethodTypeDescription
getMessage()JsonElementThe signal sent on the channel.
getSubscription()StringThe channel group or wildcard subscription match (if exists).
getChannel()StringThe channel for which the signal belongs.
getTimetoken()LongTimetoken for the signal.
getUserMetadata()ObjectUser metadata.
  1. 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();
  2. Requires Stream Controller add-on XRequires that the Stream Controller 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.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    pubnub.subscribe()
        .channels(Arrays.asList("my_channel1","my_channel2" )) // subscribe to channels information
        .execute();
  3. Requires Presence add-on XRequires that the Presence 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.

    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();
    if (presence.getEvent().equals("join")) {
    	presence.getUuid(); // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
    	presence.getTimestamp(); // 1345546797
    	presence.getOccupancy(); // 2
    }
    
     if (presence.getEvent().equals("leave")) {
        presence.getUuid(); // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
    	presence.getTimestamp(); // 1345546797
    	presence.getOccupancy(); // 2
    }
    if (presence.getEvent().equals("timeout")) {
    	presence.getUuid(); // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
    	presence.getTimestamp(); // 1345546797
    	presence.getOccupancy(); // 2
    }
    
    {
    	"action": "state-change",
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"timestamp": 1345549797,
    	"data": {
    		"isTyping": true
    	}
    }
    
    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 PubNub Admin Dashboard.

    • 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
    }
    
  4. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked 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.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., 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 (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    pubnub.subscribe()
    	.channels(Arrays.asList("foo.*")) // subscribe to channels information
    	.execute();
  5. Requires Presence add-on XRequires that the Presence 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.
    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){
    			complexData data = new complexData();
    			data.fieldA = "Awesome";
    			data.fieldB = 10;
    			pubnub.setPresenceState()
    				.channels(Arrays.asList("awesomeChannel"))
    				.channelGroups(Arrays.asList("awesomeChannelGroup"))
    				.state(data).async(new PNCallback<PNSetStateResult>() {
    					@Override
    					public void onResponse(PNSetStateResult result, PNStatus status) {
    						// handle set state response
    					}
    				});
    		}
    	}
    
    	@Override
    	public void message(PubNub pubnub, PNMessageResult message) {
    
    	}
    
    	@Override
    	public void presence(PubNub pubnub, PNPresenceEventResult presence) {
    
    	}
    });
    
    pubnub.subscribe().channels(Arrays.asList("awesomeChannel"));
  6. Requires Stream Controller add-on XRequires that the Stream Controller 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.
    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();
  7. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are 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.
    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();
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 the channel(s) 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 the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the Android V4 SDK
  1. ParameterTypeRequiredDescription
    channelsArrayOptionalUnsubscribe to channels, Either channel or channelGroup is required
    channelGroupsArrayOptionalUnsubscribe to channel groups, Either channel or channelGroup is required
    execute()CommandYesCommand that will execute unsubscribe.
Unsubscribe from a channel:
pubnub.unsubscribe()
    .channels(Arrays.asList("my_channel"))
    .execute();
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.
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
    }
}
  1. Requires Stream Controller add-on XRequires that the Stream Controller 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.
    pubnub.unsubscribe()
        .channels(Arrays.asList("ch1", "ch2", "ch3"))
        .channelGroups(Arrays.asList("cg1", "cg2", "cg3"))
        .execute();
    @Override
    public void presence(PubNub pubnub, PNPresenceEventResult presence) {
        if (presence.getEvent().equals("leave")) {
            presence.getTimestamp(); // 1345546797
            presence.getOccupancy(); // 2
            presence.getUuid(); // left_uuid
        }
    }
    
  2. pubnub.unsubscribe()
        .channelGroups(Arrays.asList("cg1", "cg2", "cg3"))
        .execute();
    @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 all channels and all channel groups
  • public final void unsubscribeAll()
pubnub.unsubscribeAll();
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

pubnub.addListener(new SubscribeCallback() {
    @Override
    public void status(PubNub pubnub, PNStatus status) {
        switch (status.getOperation()) {
            // let's combine unsubscribe and subscribe handling for ease of use
            case PNSubscribeOperation:
            case PNUnsubscribeOperation:
                // note: subscribe statuses never have traditional
                // errors, they just have categories to represent the
                // different issues or successes that occur as part of subscribe
                switch (status.getCategory()) {
                    case PNConnectedCategory:
                        // this is expected for a subscribe, this means there is no error or issue whatsoever
                    case PNReconnectedCategory:
                        // this usually occurs if subscribe temporarily fails but reconnects. This means
                        // there was an error but there is no longer any issue
                    case PNDisconnectedCategory:
                        // this is the expected category for an unsubscribe. This means there
                        // was no error in unsubscribing from everything
                    case PNUnexpectedDisconnectCategory:
                        // this is usually an issue with the internet connection, this is an error, handle appropriately
                    case PNAccessDeniedCategory:
                        // this means that PAM does allow this client to subscribe to this
                        // channel and channel group configuration. This is another explicit error
                    default:
                        // More errors can be directly specified by creating explicit cases for other
                        // error categories of `PNStatusCategory` such as `PNTimeoutCategory` or `PNMalformedFilterExpressionCategory` or `PNDecryptionErrorCategory`
                }

            case PNHeartbeatOperation:
                // heartbeat operations can in fact have errors, so it is important to check first for an error.
                // For more information on how to configure heartbeat notifications through the status
                // PNObjectEventListener callback, consult <link to the PNCONFIGURATION heartbeart config>
                if (status.isError()) {
                    // There was an error with the heartbeat operation, handle here
                } else {
                    // heartbeat operation was successful
                }
            default: {
                // Encountered unknown status type
            }
        }
    }

    @Override
    public void message(PubNub pubnub, PNMessageResult message) {
        String messagePublisher = message.getPublisher();
        System.out.println("Message publisher: " + messagePublisher);
        System.out.println("Message Payload: " + message.getMessage());
        System.out.println("Message Subscription: " + message.getSubscription());
        System.out.println("Message Channel: " + message.getChannel());
        System.out.println("Message timetoken: " + message.getTimetoken());
    }

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

    }

    @Override
    public void signal(PubNub pubnub, PNSignalResult pnSignalResult) {
        System.out.println("Signal publisher: " + signal.getPublisher());
        System.out.println("Signal payload: " + signal.getMessage());
        System.out.println("Signal subscription: " + signal.getSubscription());
        System.out.println("Signal channel: " + signal.getChannel());
        System.out.println("Signal timetoken: " + signal.getTimetoken());
    }
    
    @Override
    public void user(PubNub pubnub, PNUserResult pnUserResult) {
        // for Objects, this will trigger when:
        // . user updated
        // . user deleted
        PNUser pnUser = pnUserResult.getUser(); // the user for which the event applies to
        pnUserResult.getEvent(); // the event name
    }

    @Override
    public void space(PubNub pubnub, PNSpaceResult pnSpaceResult) {
        // for Objects, this will trigger when:
        // . space updated
        // . space deleted
        PNSpace pnSpace = pnSpaceResult.getSpace(); // the space for which the event applies to
        pnSpaceResult.getEvent(); // the event name
    }

    @Override
    public void membership(PubNub pubnub, PNMembershipResult pnMembershipResult) {
        // for Objects, this will trigger when:
        // . user added to a space
        // . user removed from a space
        // . membership updated on a space
        JsonElement data = pnMembershipResult.getData(); // membership data for which the event applies to
        pnMembershipResult.getEvent(); // the event name
    }
});
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) {

    }
};

pubnub.addListener(subscribeCallback);

// some time later
pubnub.removeListener(subscribeCallback);
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
	public void message(PubNub pubnub, PNMessageResult message) {

	}

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

	}
};

pubnub.addListener(subscribeCallback);
CategoriesDescription
PNNetworkIssuesCategoryA subscribe event experienced an exception when running.
PNReconnectedCategorySDK was able to reconnect to pubnub.
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAcknowledgmentCategoryUsed API report success with this status category.
PNAccessDeniedCategoryRequest failed because of access error (active PAM). status.errorData.channels or status.errorData.channelGroups contain list of channels and/or groups to which user with specified auth key doesn't have access.
PNTimeoutCategoryUsed API didn't received response from server in time.
PNDisconnectedCategoryClient did unsubscribe from specified real-time data channels.
PNUnexpectedDisconnectCategoryPreviously started subscribe loop did fail and at this moment client disconnected from real-time data channels.
PNBadRequestCategoryRequest can't be completed because not all required values has been passed or passed values has unexpected data type. PubNub Java SDK will send PNBadRequestCategory when some parameter is missing like message, channel, subscribe key, publish key.
PNMalformedFilterExpressionCategorySubscription request can't be processed by PubNub service because filter expression malformed and can't be evaluated.
PNMalformedResponseCategoryRequest received in response non-JSON data. It can be because of publish WiFi hotspot which require authorization or proxy server message.
PNDecryptionErrorCategoryHistory API may return this status category in case if some messages can't be decrypted. Unencrypted message will be returned in status.associatedObject where associatedObject is PNMessageData which contain channel and message properties.
PNTLSConnectionFailedCategoryTLS handshake issues and in most cases because of poor connection quality and packets loss and delays.
PNTLSUntrustedCertificateCategoryOrigin to which client tried to connect has untrusted certificate.
PNRequestMessageCountExceededCategoryIf requestMessageCountThreshold is set, this status event will arrive each time when client receive more messages when it has been specified for PNConfiguration property.
PNUnknownCategory

PubNub SDK could return this Category if the URL was not found. Check the channel or channelGroup.

This call throw this Error:

pubNub.subscribe()
    .withPresence()
    .channels(Arrays.asList("awesomeChannel/"))
    .execute();


Go to Presence