androidsocketsudpudpclient

Use Threads vs. Handlers vs. AsyncTask in an Android App sending UDP datagrams


I have the following problem to solve in the development of my first Android App:
The app receives ~100 measurements per second from a Bluetooth-enabled sensor. These measurement values should now be streamed to another device via the network.

Since the sensor values should be available as fast as possible, I intend to send them from the smartphone to the network device via UDP. However, I am unsure what the best approach to setup the UDP socket and sending logic is.

I have found several multi-threaded examples using structures like Thread, Handler, AsyncTask, Runnable etc. but none of the examples seem really fitting to my problem. For instance, some seem to spawn one thread per message to be sent - which seems like a lot of unnecessary overhead for my application scenario.

My idea would be to let the main thread spawn a sub-thread that creates the UDP socket and keeps checking a queue of incoming messages and sends the received messages in the queue via UDP Datagrams. I would be happy and thankful for some pointers which structures for handling threads would enable this.


Solution

  • You have a real mix of technologies there, and they don't fill the same slot. So no wonder you're confused.

    Runnable- this is just a function that can be saved and called whenever. It may be of use in writing a solution, but it provides no asynchronous ability whatsoever by itself.

    Handler- a handler is a message queue that runs on a particular thread. That thread must have set up a Looper. If you want to post messages from one thread to another, this can be the message passing mechanism, but it doesn't provide asynchronous ability in and of itself.

    Thread- is an actual thread. Its a function that can run in parallel to your main thread. This is probably what you actually want.

    AsyncTask- Basically a thread that runs some code on the main thread before and after running some code. It removes the burden of doing that message passing yourself. This is a simplification, but its a good enough explanation. AsyncTasks should only be used for 1 off quick operations. While you'll see examples of it being used for HTTP transfers, it really shouldn't be.

    Basically what you want is a Thread for the asynchronous part, with a method to pass messages to that thread. A Thread with its own Looper and a Handler for that looper would work well. Then the Thread can just read messages off that Handler, and the sensor reading code can post it to the handler. The Thread itself will run in the background when it has work to do, until you interrupt it to end the Thread at shutdown time.