In this post I will explain to you how we can connect to WebSocket in our Android application using OKHttp. In my last post, I will explain how we can use OkHttp in our Android application to get data from API. Now in this post, we can connect to WebSocket using OKHttp. Now without wasting any time, we start building our application.

Step 1. Create a new Android application on the android studio.

Step 2. Install OKHttp library in your project open project app build.gradle and implement OKHttp library

Step 3. Now open your layout file (main_activity.xml) file and create a button inside as shown below.

Step 4. Now in this step, we can create a WebSocket in our MainActivity.java. Before creating WebSocket don’t forget to add Internet permission in AndroidManifest.xml file

For this example, I am using the WebSocket connection of Coinbase. Now we can function in which we can connect to WebSocket.

If you ever work with WebSocket you can easily understand above code we have the same function as we have in web socket.

Complete Code of WebSocket Android

Hope this post helps you.