Search code examples
androidtcpbidirectional

Better way to create bidirectional communication


I recently did a project on Android 3.2 to send strings to a server in my PC with a TCP connection. I had to do a thread to achieve this, something that I didn’t have to do in a Java program. I also used the AsyncTask method, but I couldn’t send information with other functions besides the doInBackground function, in which I created the socket connection.

To send the strings, I created a loop in the doInBackground function, so it was waiting to receive a new message to send to the computer all the time. The problem with this is that I can’t do bidirectional communication. After this project, I continued to try to send the string with other function besides the doInBackground function in which. Finally, I was able to succeed with Android 1.6.

It’s a shame that this method can’t be used in superior versions of Android, because of the need of threads and also that you need to send the message in the same function you create the socket connection.

I was wondering if there is a better way to perform duplex operations in newer versions of Android.


Solution

  • You can use Threads in any android version.

    The right way to do what you want, would be to create a Service ( http://developer.android.com/reference/android/app/Service.html ) and use separate Threads in the Service to send and to recieve data.