But first – why? I did it because I wanted to issue a quickie without setting up a service. Some folks on the
internet say to use asyncTask first.
0. Create a way for the running thread to talk with the outside world via messages
1. The class that implements runnable – it is the thing that does the work
2. An instance of thread that has #1’s runnable with it
3. A way for the runnable to communicate with the application
4. Special bonus – shutdown, and restart
In this instance, we will make a runner that ticks the seconds since
the app starts/ends(hooked to the onResume, onPause functions)
0. Create a way for the running thread to talk with the outside world via messages
At the top of the activity declare some message type codes
public static final int MSG_SEC_INT = 1;
Then the messaage handler inline…
// The Handler that gets information back from the Socket private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SEC_INT: int ct=msg.arg1; Log.i(TAG, "Message CT: "+ct); break; } } };
1. The class that implements runnable – this is the thing that does the work. Note the graceful exit from the run loop using the isDone variable(only changed in cancel())
private class TickTick implements Runnable { long count; int isDone; public TickTick() { count=0; isDone=0; } public void run() { // do this until an exception occurs while (isDone==0) { try { Thread.sleep(1000); count++; mHandler.obtainMessage(MSG_SEC_INT, count,0); // return two generic ints, our count and nothing important(0). Can be more elaborate like objects, etc see android documentation. .sendToTarget(); }catch(InterruptedException iEx){ isDone=1; } } } /* Call this from the main activity to shutdown the connection */ public void cancel() { try { // yeah, this is silly for try-catch but you know its useful for io operations,etc. isDone=1; } catch (IOException e) { Log.e(TAG, "Error when closing the TickTick"); } } } /* end runnable */
3. A way for the runnable to communicate with the application
// global declaration TickTick runner=null; Thread tickThread=null;
And in the activities start routine. Good candidates are onStart,onCreate, onResume. I chose onResume.
runner=new TickTick(); tickThread=new Thread(runner; tickThread.start(); //
4. Special bonus for shutdown
best place for this is onPause, onStop, onDestroy – we use on Destroy
public void onPause(){ /* // use me to interrupt the thread without waiting for nice clean shutdown if(tickThread!=null){ thread.interrupt(); } */ runner.cancel(); // use cancel to give the thread a chance to die naturally thread.join(5000); // and give it 5 seconds to try super.onPause(); }