Android, creating a simple thread that will updated my seconds counter
Create a Handler in your UI thread, then in the worker thread send a message to the handler (Handler.sendMessage(...)).
The message will be processed on your UI thread, so you can update the text widget correctly. Like this:
private Handler myUIHandler = new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what == some_id_you_created) { //Update UI here... } }};Then in your thread, to send a message to the handler you do this:Message theMessage = myHandler.obtainMessage(some_id_you_created);myUIHandler.sendMessage(theMessage);//Sends the message to the UI handler.
For this kind of thing, it is a waste to use another thread; it is just a waste and makes it so you have to dael with multithreading issues. Instead, just use Handler.sendDelayedMessage():
static final int MSG_DO_IT = 1;static final long TIME_BETWEEN_MESSAGES = 10 * 1000; // 10 secondsHandler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_DO_IT: { // Update your UI here... Message newMsg = obtainMessage(MSG_DO_IT); sendMessageDelayed(newMsg, TIME_BETWEEN_MESSAGES); } break; } }}@Overridevoid onResume() { super.onResume(); // Start the timer, executing first event immediately. Message newMsg = mHandler.obtainMessage(MSG_DO_IT); mHandler.sendMessage(newMsg);}@Overridevoid onPause() { super.onPause(); // Stop the timer. mHandler.removeMessages(MSG_DO_IT);}
Note that this implementation will have some drift -- the actual time between messages is TIME_BETWEEN_MESSAGES + (time to dispatch message). If you need something that won't drift, you can do the timing yourself by using Hander.sendMessageAtTime() and incrementing the new time with a constant value each time, starting with an initial time you get with SystemClock.uptimeMillis() in onResume().
There is a great example of a Timer built using AsyncTask and a Handler with the postDelayed method.
You are correct that updating the UI from a background is a no-no.