CODEX

Android Tutorial Part 2 using Java-WebSocket with Kotlin

Fahri Can
CodeX
Published in
4 min readSep 21, 2020

--

This is the second part of the tutorial: Using Java-WebSocket with Kotlin.

In Part 1 we set up Gradle dependencies, took a look at the websocket feed of Coinbase Pro. Then created the layout to display the price. Started to implement the anonymous class WebSocketClient and finished to implement onOpen() method.

Let us continue with onMessage()

We are finished with onOpen() hop next to onMessage(). At the method, onMessage() start here also with a log statement. Then create the method for setting up the Bitcoin Euro price on the UI.

override fun onMessage(message: String?) {
Log.d(TAG, "onMessage: $message")
setUpBtcPriceText(message)
}

The method setUpBtcPriceText(message) is not created yet. Let us start to implement it. The given parameter should first be checked if it is not null. Create a moshi instance. Create the adapter instance in the next line. Then pass the JSON to the adapter. For assigning the price to the TextView with the id of btc_price_tv it has to happen on a thread that has access to the UI. We have to use runOnUiThread {}.

Next onClose()

Same as onMessage() start here also with a log statement, then create the method for unsubscribing from the websocket.

override fun onClose(code: Int, reason: String?, remote: Boolean) {
Log.d(TAG, "onClose")
unsubscribe()
}

But before start implementing the method. First, let us take a look at the official Coinbase Pro documentation.

screenshot from Coinbase Pro websocket documentation

Okay, we need again our field webSocketClient which sends the message for unsubscribing.

Last method onError()

At the moment we have implemented onOpen(), onMessage() and onClose(). The method onError() is the easiest to implement. Here we only want to log when an error occurs.

override fun onError(ex: Exception?) {
Log.e(TAG, "onError: ${ex?.message}")
}

Finish implementing initWebSocket()

We are almost done. Hop back to the method initWebSocket(). The current implementation looks like this:

private fun initWebSocket() {
val coinbaseUri: URI? = URI(WEB_SOCKET_URL)

createWebSocketClient(coinbaseUri)
}

Below the method createWebSocketClient(coinbaseUri). Add a local variable of type SSLSocketFactory. This local variable is required for connecting to a secure websocket because the “wss” from “wss://ws-feed.pro.coinbase.com” stands for websocket secure. The connection is encrypted. If it would be “ws” the connection would be in cleartext.

val socketFactory: SSLSocketFactory = SSLSocketFactory.getDefault() as SSLSocketFactory

Below the local variable of type SSLSocketFactory we need to set the socket factory for our field webSocketClient. At a new line, we can call the connect() method of our field webSocketClient to establish the connection to “wss://ws-feed.pro.coinbase.com”.

webSocketClient.setSocketFactory(socketFactory)
webSocketClient.connect()

Allow Internet permission

Before we can run the app to see if everything works. We have to open AndroidManifest.xml and add permission for Internet access.

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

Open Logcat to see that everything works

Okay, run now the app and you should see something like this:

price in Euro for one Bitcoin

Then open Logcat and set it to Debug and type in search “Coinbase” there you should see something like this:

onOpen() and onMessage()

Then put the app in the background or open another app on your device. Then you should see something like this:

onClose() and onError()

The connection will be closed when the screen is not in the foreground and this will save battery and data volume. The logic was implemented in the first part, with overriding onPause().

override fun onPause() {
super.onPause()
webSocketClient.close()
}

Now put the app again in the foreground and watch Logcat. You will see everything starts again.

That’s it! Congratulation on marking it so far! I hope this tutorial was useful for you. Here is the completed project, you might checkout branch part2:

Acknowledgments

Special thanks to Coinbase Pro for providing documentation for their websocket feed.

--

--

Fahri Can
CodeX

Android Dev | Blogger | AI & Crypto Enthusiast