This guide shows you how to subscribe to PieSocket channels on Android using Java or Kotlin.
We will be using OkHttp library to achieve this.
Start by creating a new dummy project on Android studio (Kotlin or Java, does not matter), then follow the steps below.
Let's start by adding OkHttp as dependency to our application, add the following code into your module-level build.gradle
file
implementation 'com.squareup.okhttp3:okhttp:3.6.0'
It is mandatory to have internet access permissions in order to connect to our server, so make sure you have added the following in your manifest. If not, 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">
Copy the following code and paste it into a file named PieSocketListener.java
in the same directory as MainActivity.kt
in your application.
package com.example.myapplication;
import android.util.Log;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
public class PieSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hello World!");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
output("Received : " + text);
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(NORMAL_CLOSURE_STATUS, null);
output("Closing : " + code + " / " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
output("Error : " + t.getMessage());
}
public void output(String text){
Log.d("PieSocket",text);
}
}
Let's add a simple button, clicking which will connect you to the PieSocket channel.
Open your activity_main.xml
file and replace its contents with this.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/connect"
style="@android:style/Widget.Holo.Light.Button"
android:layout_width="333dp"
android:layout_height="85dp"
android:layout_centerInParent="true"
android:text="Connect to PieSocket"
android:textSize="17sp" />
</RelativeLayout>
New Android studio projects create MainActivity.kt
by default instead of MainActivity.java
, so the following example is in Kotlin.
Open your MainActivity.kt
file and replace the onCreate
method with the following code
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val client: OkHttpClient = OkHttpClient();
connect.setOnClickListener{
Log.d("PieSocket","Connecting");
var apiKey = "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm"; //Demo key, get yours at https://piesocket.com
var channelId = 1;
val request: Request = Request
.Builder()
.url("wss://demo.websocket.me/v3/$channelId?api_key=$apiKey¬ify_self")
.build()
val listener = PieSocketListener()
val ws: WebSocket = client.newWebSocket(request, listener)
}
}
The MainActivity.kt
file in your project should look like this
package com.example.myapplication
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val client: OkHttpClient = OkHttpClient();
connect.setOnClickListener{
Log.d("PieSocket","Connecting");
var apiKey = "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm";
var channelId = 1;
val request: Request = Request
.Builder()
.url("wss://demo.websocket.me/v3/$channelId?api_key=$apiKey¬ify_self")
.build()
val listener = PieSocketListener()
val ws: WebSocket = client.newWebSocket(request, listener)
}
}
}
Run the application, open Logcat
and in the search-box that filters out log messages type PieSocket
, to filter out log messages we are interested in.
Now, click on Connect to PieSocket
button in the application and you should start to see the logs coming from the WebSocket channel.
Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.