Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I keep a connection thread alive? (Do I need to use a daemon?)
    primarykey
    data
    text
    <p>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.</p> <pre><code>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(); } }. </code></pre> <p>For ages I was scratching my head wondering why I never saw the value of <code>INNER_TAG</code> appear in my logs after touch events. I could use log-debugging to trace the execution into the <code>coordHandler!=null</code> block, but the handler never seemed to fire.</p> <p>Then it struck me: the thread is probably exiting after completing the connection. <strong>D'uh!</strong> Not quite sure what I thought was happening before, but I'll blame it on a belief that <code>Loop</code> was doing something magical.</p> <p>So my question is: How can I keep my thread running? The official <a href="http://developer.android.com/reference/java/lang/Thread.html" rel="nofollow">Android dev reference on threads</a> briefly mentions that</p> <blockquote> <p>A Thread can also be made a daemon, which makes it run in the background.</p> </blockquote> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload