I am building an Android App that will communicate over TCP with a server. I have a few ideas for implementation and I don’t know which way would be best to go. I am new at this and my design is constantly evolving as I learn new things, so now I am looking for advice for how to best implement a solution to fulfill my goal.
Goal: Be able to:
- send data to a server
-
Send data to a server and read the servers response.
- Some information I send will be to give the server information, other will be to request information from the server.
Possible implementations:
- Thread Run() method constantly loops through checking if my send queue has something to send (and sending it if it does) then checking if I have anything to read back in.
- Will this drain battery/burn CPU?
- Create a new thread each time I want to send/receive, the let it die once I have done ‘send’ or ‘send + receive’
- How should I synchronize the threads interactions with my one socket? Block making the next thread until this one finishes?
- Make a thread and call a send or send + receive method withing that thread each time I need to write or write + read
- How do I keep the thread alive without burning battery/CPU?
- should I use a queue to handle requests for transmitting data and should I synchronize reading from it until the current read/write is finished?
Any additional pointers, links, or warnings about potential issues would be much appreciated. Sample code is especially appreciate as I am just starting out with this. Thank you.
As you’ve pointed there are several ways of achieving this, each of them has its advantages and weaknesses.
Leaving a connection open, or re-sending them very often will definitely make a difference in battery duration. If this is your case I’d think about batching some requests into one every certain amount of time. Here is a interesting article about that.
I wrote some days ago about an approach I’m using very often which works pretty nicely. It can be as simple as it looks or set the basis for a whole API communication engine for your Android app. It is up to your needs. It is basically executing your requests in a pool of background threads, controlled by a service and notified within your activities or whatever you need.
Whenever you need to push a new requests it as simple as enqueueing it and setting the callback.
If you think that might work for you here I leave you a pair of links diving deeper into this.
http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/
http://ugiagonzalez.com/2012/08/03/using-runnables-queues-and-executors-to-perform-tasks-in-background-threads-in-android/
Hope it helps.