9

Android noob here. I learn the best by seeing the source code of a functional example, but I have been unable to find a simple-but-complete example of using a socket in its own thread.

I have an Android service that needs to communicate with the Internet. I want to open a TCP socket that connects to a server on the Internet. The service needs to send data to the Internet, and data coming back from the net will need to go to the service. Since the service is doing other things as well, the socket connection needs to live in its own thread.

Any idea where I could find an example of a socket in a thread with communication to/from the socket?

Thanks

enter image description here

2 Answers 2

15
+50

You simply need to create an async task that communicates in the background and then updates the UI thread as needed. Here is the background thread to get information from a socket and update a text view with the number of bytes it receivers

  public class InternetTask extends AsyncTask<Void, Integer, Void> {

    private WeakReference<TextView> mUpdateView;

    public LoginTask(TextView view) {
        this.mUpdateView = new WeakReference<TextView>(view);
    }

    @Override
    protected Void doInBackground() {

        try {
            Socket socket = new Socket("127.0.0.1", 80);
                    InputStream is = socket.getInputStream();

                    byte[] buffer = new byte[25];
                    int read = is.read(buffer);
                    while(read != -1){
                         publishProgress(read);
                         read = is.read(buffer);
                    }

                    is.close();
                    socket.close();



        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        if(mUpdateView.get() != null && values.length > 0){
                     mUpdateView.get().setText(values[0].toString());
                }
    }

}

And here is how you would kick that thread off

public class TestTab extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.someLayout);

            TextView textView = (TextView)findViewById(R.id.someid);
            InternetTask task = new InternetTask(textView);
            task.execute();

    }
}
8
  • Is there a way to send additional data to an AsyncTask once it has been started so that data can be sent out the socket? I see how to use publishProgress and onProgressUpdate to get data from the background thread to the UI thread, but I don't see how to go the other way while the task is running. Feb 24, 2011 at 3:33
  • 2
    You can define whatever other methods on your async task that you want. Just know that the doInBackground() method will be the only one executed on a separate thread. You can also pass in the data you want to send in the constructor or to the execute() method. Feb 24, 2011 at 19:42
  • When I open a socket in doInBackground(), that new thread is going to be blocking until data comes in on the socket. When data comes in, I can send it to the UI thread via publishProgress. Since the socket was created on that worker thread, how would I send data to the socket from the UI thread? I'm dealing with a data stream, so sending parameters with the execute() command is good, but I need to continually send data to the socket. Feb 25, 2011 at 5:06
  • You treat the task like any other object, and give data to it in the normal way. It just runs in a separate thread. Feb 25, 2011 at 15:30
  • 2
    i think there is a typo in InternetTask constructor. it should be public InternetTast(TextView view) not public LoginTask(TextView view)
    – Jalal
    Aug 19, 2012 at 11:51
8

Here is a long blog about this subject, where both the server and client parts are showing, with the socket communication going over a separate thread.

http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

One thing to be aware of is that if you are passing ints you may run into a byte-order problem, so, just do some testing and I would suggest you ensure that the server sends in the format that the Android needs, in case you have servers on more than one OS.

For a simple way, on the Android to find the byte order you can use this: http://developer.android.com/reference/java/nio/ByteOrder.html

According to this article, byte order may be swapped for optimization: http://en.wikipedia.org/wiki/Dalvik_(software)

2
  • That is the clearest code I've seen showing how to create sockets. However, while the server example shows how to send data back to the UI thread (via the handler), neither of the examples show how to move data from the UI thread to the socket thread. Dec 5, 2010 at 6:25
  • You could use View.post to get back to the UI thread, but this page may help you in other ways: developer.android.com/guide/appendix/faq/… Dec 5, 2010 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.