I am building an android app that communicates with a server on a regular basis as long as the app is running.
I do this by initiating a connection to the server when the app starts, then I have a separate thread
for receiving messages called ReceiverThread
, this thread
reads the message from the socket
, analyzes it, and forwards it to the appropriate part of the application.
This thread
runs in a loop, reading whatever it has to read and then blocks on the read()
command until new data arrives, so it spends most of it's time blocked.
I handle sending messages through a different thread, called SenderThread
. What I am wondering about is: should I structure the SenderThread
in a similar fashion? Meaning should I maintain some form a queue for this thread, let it send all the messages in the queue and then block until new messages enter the queue, or should I just start a new instance of the thread every time a message needs to be sent, let it send the message and then "die"? I am leaning towards the first approach, but I do not know what is actually better both in term of performance (keeping a blocked thread in memory versus initializing new threads), and in terms of code correctness.
Also since all of my activities need to be able to send and receive messages I am holding a reference to both threads in my Application
class, is that an acceptable approach or should I implement it differently?
One problem I have encountered with this is that sometimes if I close my application and run it again I actually have two instances of ReceiverThread, so I get some messages twice.
I am guessing that this is because my application did not actually close and the previous thread was still active (blocked on the read()
operation), and when I opened the application again a new thread was initialized, but both were connected to the server so the server sent the message to both. Any tips on how to get around this problem, or on how to completely re-organize it so it will be correct?
I tried looking up these questions but found some conflicting examples for my first question, and nothing that is useful enough and applies to my second question...
Thread#interrupt()
(+Socket#close()
) can be used to stop it but the hard part is to keep track of whether Application is running or just idle in background. Each activity can do that fromonStart
ononStop
for example. – Schacker