PieSocket Android SDK

PieSocket offers the Channels Android SDK for easy integration into Android applications, Kotlin or Java.

Channels Android SDK is a Java library and it can be used as a standalone WebSocket client in any Java project.

Channels SDK implements auto-reconnections, among other best WebSocket practices.

The following is an example of how to subscribe to events on Android.

Getting started

Create an Android Studio project and follow the steps below.

The code shown below can be put directly inside an Activity (say MainActivity.java). But, it's best to create a Foreground service and initialise PieSocket inside it, so the connection doesn't drop when the activity stops, or the app is closed.

Add dependency

Let's start by adding thePieSocket Android SDK as a dependency to your application.

Gradle (Kotlin)

implementation("com.piesocket:channels-sdk:1.0.5")

Gradle (Java)

implementation 'com.piesocket:channels-sdk:1.0.5'

Maven

<dependency>
    <groupId>com.piesocket</groupId>
    <artifactId>channels-sdk</artifactId>
    <version>1.0.5</version>
</dependency>

Add permissions

It is mandatory to have internet access permissions to connect to the PieSocket server, so make sure you have added the following in the app manifest. Copy the following code and paste it before the application tag

<uses-permission android:name="android.permission.INTERNET" />

Also, you need to allow clear-text traffic. To do so, add the following attribute on your application tag

android:usesCleartextTraffic="true"

Your application tag should look something like this

<uses-permission android:name="android.permission.INTERNET" />

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"        
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

Usage

You are now ready to use PieSocket Channels in your application.

Initialize PieSocket

Define your API Key, Cluster ID and pass it to the PieSocket class.

Get your API key and Cluster ID here: Create a PieSocket account

PieSocketOptions options = new PieSocketOptions();
options.setClusterId("demo");
options.setApiKey("VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV");

PieSocket piesocket = new PieSocket(options);

To see the full list of available configuration options,

See: PieSocket Configuration Options

A setter method is available on the PieSocketOptions class for all the options listed in the linked page.

Subscribe to a Channel

Subscribe to a Channel with PieSocket's managed WebSocket server.

Channel channel = piesocket.join("chat-room");

Here chat room is what we call a roomId. You need this ID to publish messages from your server.

See: How to choose a Room ID

Listen to an event

You can attach multiple PieSocketEventListener instances to an event by using the code below multiple times. All listeners will be called when the event is fired.

channel.listen("new-message", new PieSocketEventListener() {
    @Override
    public void handleEvent(PieSocketEvent event) {
        Log.d("PIESOCKET-SDK", "New message received: "+ event.getData());
    }
});

There are system events like system:connected, system:member_joined, etc. You can listen to these events to build a beautiful real-time connected experience.

See a list of all system events here: All system events

Remove an event listener

Pass the same PieSocketEventListener instance used to listen to the event in the following method to remove a listener.

channel.removeListener("new-message", new PieSocketEventListener() {
    @Override
    public void handleEvent(PieSocketEvent event) {
        Log.d("PIESOCKET-SDK", "New message received: "+ event.getData());
    }
});

Remove all event listeners

To stop listening for an event, and remove all of the listeners, use the following method.

channel.removeAllListeners("new-message");

Publish Events

Use the publish method to publish an event from the client itself.

You must enable client-to-client communication settings for the PieSocket cluster to make this work; in new clusters, it is enabled by default.

channel.listen("system:connected", new PieSocketEventListener() {
    @Override
    public void handleEvent(PieSocketEvent event) {
        //Channel is connected

        //Construct an event
        PieSocketEvent newMessage = new PieSocketEvent("new-message");
        newMessage.setData("Hello!");

        //Publish the event
        channel.publish(newMessage);
    }
});

Developers usually publish events from the backend server.

See: How to publish events from the server

Room members

You can see who is in a room, get system:member_joined to fire and track when people leave by enabling Presence features in a room.

pieSocketOptions.setPresence(true);

List all members

To get a JSONArray containing all members of the room, use the following code

JSONArray members = channel.getAllMembers()

The same is possible from your server, see the REST API section

Get the current member

To get information about the current member, use the following code

JSONObject me = channel.getCurrentMember()

User Authentication

PieSocket lets you block unauthorised connections and identify users with the help of JWT authentication tokens.

To learn more, like how to set a User ID, what Private Channels are, etc.

See the: Authentication guide

Set Authentication Endpoint

Set an Authentication URL that generates and responds with JWT tokens. Channels SDK makes a POST request to this URL with Channel information, everytime an user tries to connect to a private room.

pieSocketOptions.setAuthEndpoint("https://mywebsite.com/generate-jwt");

The URL should respond with the following JSON on successful authentication.

{"auth":"*************"}

Set JWT Token

To skip the authEndpoint call, and set the JWT yourself, use the following method.

pieSocketOptions.setJwt("*****************");

Leave a channel

To unsubscribe from a Channel and close the ongoing WebSocket connection, use thefollowing code.

All event listeners on this Channel will be removed.

piesocket.leave("chat-room");

Stand-alone usage

You can use the PieSocket Android SDK to connect to third-party WebSocket servers as well. Skip, the configuration part and create a Channel instance as shown below.

You will miss out on features like Private Channels, Presence Channels, Multiple Rooms, etc. Stick to PieSocket's managed WebSockets to save upto 60% costs.

Channel channel = new Channel("wss://example.com", true);

Example

Following is a sample Activity, it logs "Channel connected" into logcat when Channels is ready to send and receive messages.

Note: Channels should generally be initialised into a foreground/background service.

package com.piesocket.android;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.piesocket.android.databinding.ActivityMainBinding;
import com.piesocket.channels.Channel;
import com.piesocket.channels.PieSocket;
import com.piesocket.channels.misc.PieSocketEvent;
import com.piesocket.channels.misc.PieSocketEventListener;
import com.piesocket.channels.misc.PieSocketOptions;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    private PieSocket piesocket;
    private Channel channel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        PieSocketOptions pieSocketOptions = new PieSocketOptions();
        pieSocketOptions.setClusterId("demo");
        pieSocketOptions.setApiKey("VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV");

        piesocket = new PieSocket(pieSocketOptions);
        channel = piesocket.join("chat-room");

        channel.listen("system:connected", new PieSocketEventListener() {
            @Override
            public void handleEvent(PieSocketEvent event) {

                Log.d("PIESOCKET-SDK", "Channel connected");

                PieSocketEvent  clientEvent = new PieSocketEvent("testevent");
                clientEvent.setData("Hello!");
                channel.publish(clientEvent);

            }
        });

        channel.listen("testevent", new PieSocketEventListener() {
            @Override
            public void handleEvent(PieSocketEvent event) {
                Log.d("PIESOCKET-SDK", "testevent was fired");
            }
        });
    }

}

Help

Facing difficulties? Use the chat box in the bottom-right corner of this page to reach us.