My Android application uses a stream to listen for socket connections from a PC connected via USB. At some point after the PC opens the connection (in response to some event controlled by the user), I want to send him some data.
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 centuries, I have been scratching my head, wondering why I have never seen the value of INNER_TAG in my magazines after touch events. I could use a debug log entry to track execution in the coordHandler!=null block, but the handler never fired.
Then it struck me: the thread probably exited after the connection was completed. D'uh! Not quite sure what I thought before, but I will blame him for Loop doing something magical.
So my question is: how can I save the stream? The official Android dev topic link briefly mentions that
A Thread can also be made a daemon that will launch it in the background.
This naturally made my feelings. (By the way, have you seen the new spider movie? That's pretty good.) Is demonization the answer? Or am I completely losing the plot?
source share