!!!!!!!!!!
PubNub Java SDK development has moved to the PubNub Kotlin SDK repository.
This repository is no longer being updated.
!!!!!!!!!!
This is the official PubNub Java SDK repository.
PubNub takes care of the infrastructure and APIs needed for the realtime communication layer of your application. Work on your app's logic and let PubNub handle sending and receiving data across the world in less than 100ms.
You will need the publish and subscribe keys to authenticate your app. Get your keys from the Admin Portal.
Integrate the Java SDK into your project:
for Maven, add the following dependency in your
pom.xml:<dependency> <groupId>com.pubnub</groupId> <artifactId>pubnub-gson</artifactId> <version>6.4.5</version> </dependency>
for Gradle, add the following dependency in your
gradle.build:implementation 'com.pubnub:pubnub-gson:6.4.5'
Configure your keys:
PNConfigurationpnConfiguration = newPNConfiguration(newUserId("myUserId")); pnConfiguration.setSubscribeKey("mySubscribeKey"); pnConfiguration.setPublishKey("myPublishKey"); PubNubpubnub = newPubNub(pnConfiguration);
// SubscribeCallback is an Abstract Java class. It requires that you implement all Abstract methods of the parent class even if you don't need all the handler methods.pubnub.addListener(newSubscribeCallback(){// PubNub status@Overridepublicvoidstatus(PubNubpubnub, PNStatusstatus){switch (status.getOperation()){// combine unsubscribe and subscribe handling for ease of usecasePNSubscribeOperation: casePNUnsubscribeOperation: // Note: subscribe statuses never have traditional errors,// just categories to represent different issues or successes// that occur as part of subscribeswitch (status.getCategory()){casePNConnectedCategory: // No error or issue whatsoever.casePNReconnectedCategory: // Subscribe temporarily failed but reconnected.// There is no longer any issue.casePNDisconnectedCategory: // No error in unsubscribing from everything.casePNUnexpectedDisconnectCategory: // Usually an issue with the internet connection.// This is an error: handle appropriately.casePNAccessDeniedCategory: // PAM does not allow this client to subscribe to this// channel and channel group configuration. This is// another explicit error.default: // You can directly specify more errors by creating// explicit cases for other error categories of// `PNStatusCategory` such as `PNTimeoutCategory` or// `PNMalformedFilterExpressionCategory` or// `PNDecryptionErrorCategory`. } casePNHeartbeatOperation: // Heartbeat operations can in fact have errors,// so it's important to check first for an error.// For more information on how to configure heartbeat notifications// through the status PNObjectEventListener callback, refer to// /docs/android-java/api-reference-configuration#configuration_basic_usageif (status.isError()){// There was an error with the heartbeat operation, handle here } else{// heartbeat operation was successful } default:{// Encountered unknown status type } } } // Messages@Overridepublicvoidmessage(PubNubpubnub, PNMessageResultmessage){StringmessagePublisher = 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())} // Presence@Overridepublicvoidpresence(@NotNullPubNubpubnub, @NotNullPNPresenceEventResultpresence){System.out.println("Presence Event: " + presence.getEvent()); // Can be join, leave, state-change or timeoutSystem.out.println("Presence Channel: " + presence.getChannel()); // The channel to which the message was publishedSystem.out.println("Presence Occupancy: " + presence.getOccupancy()); // Number of users subscribed to the channelSystem.out.println("Presence State: " + presence.getState()); // User stateSystem.out.println("Presence UUID: " + presence.getUuid()); // UUID to which this event is relatedpresence.getJoin(); // List of users that have joined the channel (if event is 'interval')presence.getLeave(); // List of users that have left the channel (if event is 'interval')presence.getTimeout(); // List of users that have timed-out off the channel (if event is 'interval')presence.getHereNowRefresh(); // Indicates to the client that it should call 'hereNow()' to get the// complete list of users present in the channel. } // Signals@Overridepublicvoidsignal(PubNubpubnub, PNSignalResultpnSignalResult){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())} // Message actions@OverridepublicvoidmessageAction(PubNubpubnub, PNMessageActionResultpnActionResult){PNMessageActionpnMessageAction = pnActionResult.getAction(); System.out.println("Message action type: " + pnMessageAction.getType()); System.out.println("Message action value: " + pnMessageAction.getValue()); System.out.println("Message action uuid: " + pnMessageAction.getUuid()); System.out.println("Message action actionTimetoken: " + pnMessageAction.getActionTimetoken()); System.out.println("Message action messageTimetoken: " + pnMessageAction.getMessageTimetoken());] System.out.println("Message action subscription: " + pnActionResult.getSubscription()); System.out.println("Message action channel: " + pnActionResult.getChannel()); System.out.println("Message action timetoken: " + pnActionResult.getTimetoken())} // Files@Overridepublicvoidfile(PubNubpubnub, PNFileEventResultpnFileEventResult){System.out.println("File channel: " + pnFileEventResult.getChannel()); System.out.println("File publisher: " + pnFileEventResult.getPublisher()); System.out.println("File message: " + pnFileEventResult.getMessage()); System.out.println("File timetoken: " + pnFileEventResult.getTimetoken()); System.out.println("File file.id: " + pnFileEventResult.getFile().getId()); System.out.println("File file.name: " + pnFileEventResult.getFile().getName()); System.out.println("File file.url: " + pnFileEventResult.getFile().getUrl())} });pubnub.publish().channel(channelName) .message(messageJsonObject) .async((result, publishStatus) ->{if (!publishStatus.isError()){// Message successfully published to specified channel. } else{// Request processing failed.// Handle message publish error// Check 'category' property to find out// issues because of which the request failed.// Request can be resent using: [status retry]; } });If you need help or have a general question, contact [email protected].