My Android application uses a thread to listen for a sockets connection from a PC connected via USB. At some point after the PC opens the connection (in response to some user driven event) I want to send some data over it.
public void onCreate(Bundle savedInstanceState) {
// SNIP: stuff and nonsense
connection = new Thread(new ServerThread());
connection.start();
}
public boolean onTouchEvent(MotionEvent event) {
// SNIP: decide what to do; create string 'coordString'
Message coordMsg = coordHandler.obtainMessage();
Bundle coordMsgData = new Bundle();
coordMsgData.putString("coords", coordString);
coordMsg.setData(coordMsgData);
if(coordHandler!=null)
{
coordHandler.sendMessage(coordMsg);
}
return false;
}
public class ServerThread extends Thread
{
public void run() {
this.setName("serverThread");
Looper.prepare();
coordHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
Log.v(INNER_TAG,"here");
}
};
// SNIP: Connection logic here
Looper.loop();
}
}.
For ages I was scratching my head wondering why I never saw the value of INNER_TAG
appear in my logs after touch events. I could use log-debugging to trace the execution into the coordHandler!=null
block, but the handler never seemed to fire.
Then it struck me: the thread is probably exiting after completing the connection. D'uh! Not quite sure what I thought was happening before, but I'll blame it on a belief that Loop
was doing something magical.
So my question is: How can I keep my thread running? The official Android dev reference on threads briefly mentions that
A Thread can also be made a daemon, which makes it run in the background.
This naturally made my *nix senses tingle. (Incidentally, have you seen the new Spiderman film yet? It's pretty good.) Is daemonisation the answer? Or have I completely lost the plot?