Presence API for PubNub Java SDK

Breaking changes in v9.0.0

PubNub Java SDK version 9.0.0 unifies the codebases for Java and Kotlin SDKs, introduces a new way of instantiating the PubNub client, and changes asynchronous API callbacks and emitted status events. These changes can impact applications built with previous versions (< 9.0.0) of the Java SDK.

For more details about what has changed, refer to Java/Kotlin SDK migration guide.

Presence enables you to track the online and offline status of users and devices in real time, and store custom state information. Presence provides authoritative information on:

  • When a user has joined or left a channel
  • Who, and how many, users are subscribed to a particular channel
  • Which channel(s) an individual user is subscribed to
  • Associated state information for these users

Learn more about our Presence feature here.

Here Now

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.

You can obtain information about the current state of a channel including a list of unique user-ids currently subscribed to the channel and the total occupancy count of the channel by calling the hereNow() function in your application.

Cache

This method has a 3 second response cache time.

Method(s)

To call Here Now you can use the following method(s) in the Java SDK:

this.pubnub.hereNow()
.channels(Array)
.channelGroups(Arrays)
.includeState(true)
.includeUUIDs(true)
ParameterTypeRequiredDefaultDescription
channelsArrayOptionalThe channels to get the here now details.
channelGroupsArraysOptionalThe channelGroups to get the here now details.
includeStateBooleanOptionalfalseIf true, the response will include the presence states of the users for channels/channelGroups
includeUUIDsBooleanOptionaltrueIf true, the response will include the UUIDs of the connected clients.
asyncConsumer<Result>YesConsumer of a Result of type PNHereNowResult

Basic Usage

Get a list of UUIDs subscribed to channel

pubnub.hereNow()
// tailor the next two lines to example
.channels(Arrays.asList("coolChannel", "coolChannel2"))
.includeUUIDs(true)
.async(result -> {
result.onSuccess(res -> {
for (PNHereNowChannelData channelData : res.getChannels().values()) {
System.out.println("---");
System.out.println("channel:" + channelData.getChannelName());
System.out.println("occupancy: " + channelData.getOccupancy());
System.out.println("occupants:");
for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
System.out.println("uuid: " + occupant.getUuid() + " state: " + occupant.getState());
}
}
show all 17 lines

Returns

The hereNow() operation returns a PNHereNowResult which contains the following operations:

MethodTypeDescription
getTotalChannels()IntTotal Channels.
getTotalOccupancy()IntTotal Occupancy.
getChannels()Map<String, PNHereNowChannelData>A map with values of PNHereNowChannelData for each channel. See PNHereNowChannelData for more details.

PNHereNowChannelData

MethodTypeDescription
getChannelName()StringChannel name.
getOccupancy()IntOccupancy of the channel.
getOccupants()List<PNHereNowOccupantData>A list of PNHereNowOccupantData, see PNHereNowOccupantData for more details.

PNHereNowOccupantData

MethodTypeDescription
getUuid()StringUUIDs of the user.
getState()ObjectState of the user.

Other Examples

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

pubnub.hereNow()
.channels(Arrays.asList("my_channel")) // who is present on those channels?
.includeState(true) // include state with request (false by default)
.includeUUIDs(true) // if false, only shows occupancy count
.async(result -> { /* check result */ });
Example Response
if (!status.isError()) {
for (PNHereNowChannelData channelData : result.getChannels().values()) {
channelData.getOccupancy(); // 3
channelData.getChannelName(); // my_channel
channelData.getOccupants(); // members of a channel
for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
occupant.getUuid(); // some_uuid;
occupant.getState(); // channel member state, if applicable
}
}
} else {
// an error occurred
status.getErrorData().getInformation();
status.getErrorData().getThrowable().printStackTrace();
}

Return Occupancy Only

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.

You can return only the occupancy information for a single channel by specifying the channel and setting UUIDs to false:

pubnub.hereNow()
.channels(Arrays.asList("my_channel")) // who is present on those channels?
.includeState(false) // include state with request (false by default)
.includeUUIDs(false) // if false, only shows occupancy count
.async(result -> { /* check result */ });
Example Response
if (!status.isError()) {
for (PNHereNowChannelData channelData: result.getChannels().values()) {
channelData.getOccupancy(); // 3
channelData.getChannelName(); // my_channel
}
} else {
// an error occurred
status.getErrorData().getInformation();
status.getErrorData().getThrowable().printStackTrace();
}

Here Now for Channel Groups

pubnub.hereNow()
.channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // who is present on channel groups?
.includeState(true) // include state with request (false by default)
.includeUUIDs(true) // if false, only shows occupancy count
.async(result -> { /* check result */ });
Example Response
if (!status.isError()) {
result.getTotalOccupancy(); // 12
} else {
// an error occurred
status.getErrorData().getInformation();
status.getErrorData().getThrowable().printStackTrace();
}

Where Now

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.

You can obtain information about the current list of channels to which a UUID is subscribed to by calling the whereNow() function in your application.

Timeout events

If the app is killed/crashes and restarted (or the page containing the PubNub instance is refreshed on the browser) within the heartbeat window no timeout event is generated.

Method(s)

To call whereNow() you can use the following method(s) in the Java SDK:

pubnub.whereNow()
.uuid(String)
ParameterTypeRequiredDescription
uuidStringOptionalUuid of the user we want to spy on.
asyncCommandYesExecute as async.

Basic Usage

You simply need to define the uuid and the callback function to be used to send the data to as in the example below.

Get a list of channels a UUID is subscribed to

pubnub.whereNow()
.async(result -> { /* check result */ });

Returns

The whereNow() operation returns a PNWhereNowResult which contains the following operations:

MethodTypeDescription
getChannels()List<String>The list of channels where the UUID is present.

Other Examples

Obtain information about the current list of channels of some other UUID

pubnub.whereNow()
.uuid("some-other-uuid") // uuid of the user we want to spy on.
.async(result -> { /* check result */ });

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

The state API is used to set/get key/value pairs specific to a subscriber uuid.

State information is supplied as a JSON object of key/value pairs.

Presence state format

Presence state must be expressed as a JsonObject. When calling setState, be sure to supply an initialized JsonObject or POJO which can be serialized to a JsonObject.

Method(s)

Set State

this.pubnub.setPresenceState()
.channels(Array)
.channelGroups(Array)
.state(HashMap)
.uuid(String)
ParameterTypeRequiredDescription
channelsArrayOptionalChannels to set state.
channelGroupsArrayOptionalChannelGroups to set state.
stateHashMapOptionalState to set.
uuidStringOptionalSet state for specific UUID.
asyncConsumer<Result>YesConsumer of a Result of type PNSetStateResult.

Get State

this.pubnub.getPresenceState()
.channels(Arrays)
.channelGroups(Arrays)
.uuid(String)
ParameterTypeRequiredDescription
channelsArraysOptionalChannel name to fetch the state.
channelGroupsArraysOptionalChannelGroups name to fetch the state.
uuidStringOptionalUUID
asyncConsumer<Result>YesConsumer of a Result of type PNGetStateResult.

Basic Usage

Set State

JsonObject state = new JsonObject();
state.addProperty("is_typing", isTyping);

pubnub.setPresenceState()
.channels(Arrays.asList(channel))
.state(state)
.async(result -> { /* check result */ });

Get State

pubnub.getPresenceState()
.channels(Arrays.asList("ch1", "ch2", "ch3")) // channels to fetch state for
.channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // channel groups to fetch state for
.uuid("suchUUID") // uuid of user to fetch, or for own uuid
.async(result -> { /* check result */ });

Returns

The setPresenceState() operation returns a PNSetStateResult which contains the following operations:

MethodTypeDescription
getState()Map<String, Object>Map of UUIDs and the user states.

The getPresenceState() operation returns a PNGetStateResult which contains the following operations:

MethodTypeDescription
getStateByUUID()Map<String, Object>Map of UUIDs and the user states.

Other Examples

Set state for channels in channel group

JsonObject state = new JsonObject();
state.addProperty("is_typing", isTyping);

pubnub.setPresenceState()
.channelGroups(Arrays.asList("cg1", "cg2", "cg3")) // apply on those channel groups
.channels(Arrays.asList("ch1", "ch2", "ch3")) // apply on those channels
.state(state) // the new state
.async(result -> { /* check result */ });

The above code would return the following response to the client:

if (presence.getEvent().equals("state-change")) {
boolean is_typing = presence.getState()
.getAsJsonObject()
.get("is_typing")
.getAsBoolean();
}
Last updated on