Skip to content
Advertisement

Android Studio Connect to Socket server

I have a server running in Java using Eclipse (Here the full code):

JavaScript

As you can see, the client sends 2 values and receives 1, the first one is for the switch, which will indicate what to exceute, for now I just have on option (checking if email exists in the ddbb), the second value is the email as the code has already entered the switch.

The server is fully working and I already tested it with a Client Test project in Eclipse (It is what I want to do in Android Studio):

JavaScript

Now what I want to do is doing the same client in Android Studio so it can connect to the server.

I tried this:

JavaScript

When I run it it does not give me any error but if I log the socket value at doInBackground’s bottom to see the socket value, it says it is null.

I also tried using Thread and Handle but I can’t get the result the server gives me back to the main thread.

Advertisement

Answer

I managed to resolve this. I just made a thread inside a “Connection” class in Android Studio.

Inside “Connection” I have some class-level variables, which I use with the thread (The thread can’t modify variables in the method the thread was created but it can read class-level variables) so the thread itself makes the connection with the socket server and saves the value taken to also a class-level variable.

In the main thread (in the same method that called the thread) I used a loop that looks at the thread status, if it has finished, reads the variable and applies it where I want.

Here the code:

JavaScript

I think another possibility could be making the thread just do the connection (and another one for closing it) and saving the socket as class-level variable, so you can send and receive from the main thread, I didn’t try it tho.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement