PubNub Android SDK 6.4.5

Unsupported docs

PubNub no longer maintains Android SDK docs, but our Java SDK or Kotlin SDK are fully compatible with the Android platform and you can use them to build mobile apps.

Get Code: Using Maven

<dependency>
<groupId>com.pubnub</groupId>
<artifactId>pubnub-gson</artifactId>
<version>6.4.5</version>
</dependency>

Get Code: Using Gradle (including Android Studio)

compile group: 'com.pubnub', name: 'pubnub-gson', version: '6.4.5'

Get Code: Jar file

To use Pubnub, simply copy the Pubnub-6.4.5 jar file into your project's libs directory.

https://github.com/pubnub/java/releases/tag/6.4.5

Get Code: Source

https://github.com/pubnub/java/

View Supported Platforms

Configuration: Proguard

# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
show all 65 lines

Hello World

Add PubNub to your project using one of the procedures defined under How to Get It

Permissions

Put these permission outside the <application> tag, preferable before the tag in the AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Required 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.

public static void main(String[] args) {
PNConfiguration.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
// publishKey from Admin Portal (only required if publishing)
configBuilder.publishKey("PublishKey");
PubNub pubnub = PubNub.create(configBuilder.build());

String channelName = "awesomeChannel";

// create message payload using Gson
JsonObject messageJsonObject = new JsonObject();
messageJsonObject.addProperty("msg", "hello");

System.out.println("Message to send: " + messageJsonObject.toString());

pubnub.addListener(new SubscribeCallback() {
show all 95 lines

Copy and paste examples

In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:

Init

Instantiate a new Pubnub instance. Only the subscribeKey is mandatory. Also include publishKey if you intend to publish from this instance, and the secretKey if you wish to perform Access Manager administrative operations from this Android instance.

Secure your secretKey

For security reasons, you should only include the secret key on a highly secured server. The secret key is only required for granting rights using our Access Manager.

When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

Initializing the client

Required 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.Builder configBuilder = PNConfiguration.builder(new UserId("yourUserId"), "yourSubscribeKey");
// publishKey from Admin Portal (only required if publishing)
configBuilder.publishKey("PublishKey");
configBuilder.secure(true);
PubNub pubNub = PubNub.create(configBuilder.build());

Listeners

Add 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 126 lines

Remove 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 lines

Handle 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 lines

Listener status events

CategoryDescription
PNNetworkUpCategoryThe SDK detected that the network is online.
PNNetworkDownCategoryThe SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers.
PNNetworkIssuesCategoryA subscribe event experienced an exception when running. The SDK isn't able to reach PubNub servers. 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.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNConnectedCategorySDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes.
PNAccessDeniedCategoryAccess Manager permission failure.
PNMalformedResponseCategoryJSON parsing crashed.
PNBadRequestCategoryThe server responded with a bad response error because the request is malformed.
PNDecryptionErrorCategoryIf using decryption strategies and the decryption fails.
PNTimeoutCategoryFailure to establish a connection to PubNub due to a timeout.
PNRequestMessageCountExceedCategoryThe SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNUnknownCategoryReturned when the subscriber gets a non-200 HTTP response code from the server.

Time

Call time() to verify the client connectivity to the origin:

pubnub.time().async(new PNCallback<PNTimeResult>() {
@Override
public void onResponse(PNTimeResult result, PNStatus status) {
// handle time result.
}
});

Subscribe

Subscribe (listen on) 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.

Publish

Publish a message to a channel:

pubnub.publish()
.message(Arrays.asList("hello", "there"))
.channel("suchChannel")
.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
}
});

Here Now

Get occupancy of who's here now on the channel by UUID:

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()
// tailor the next two lines to example
.channels(Arrays.asList("coolChannel", "coolChannel2"))
.includeUUIDs(true)
.async(new PNCallback<PNHereNowResult>() {
@Override
public void onResponse(PNHereNowResult result, PNStatus status) {
if (status.isError()) {
// handle error
return;
}

for (PNHereNowChannelData channelData : result.getChannels().values()) {
System.out.println("---");
System.out.println("channel:" + channelData.getChannelName());
show all 23 lines

Presence

Subscribe to real-time Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:

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.subscribe()
.channels(Arrays.asList("my_channel")) // subscribe to channels
.withPresence() // also subscribe to related presence information
.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.

History

Retrieve published messages from archival storage:

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.

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) {

}
});

Unsubscribe

Stop subscribing (listening) to 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.

Destroy

For more details, please see the Destroy section.

pubnub.destroy();
Last updated on