1

If I need to update UI components ( like textview) every second as long as the activity is visible. Would you recommend creating a thread (with thread.sleep) which does postOnUi call OR do I use handler with postDelayed?

I am not sure which would be more efficient provided that I have multiple textviews

Thanks?

Snake
  • 14,228
  • 27
  • 117
  • 250

1 Answers1

2

I think you're mixing up some concepts. Handler's postDelayed() indeed will run a Runnable after some time lapse, but only once.

For what you want to do you've several choices:

  • Sleeping the Thread is one of them. A disatvantage of this is that the Thread might cause an exception and this way your execution could become unstable. Also, you'll have just one Thread and you won't free it up even if it's sleeping, so you're using resources that you might not need at a time.
  • Another approach is using an AsyncTask. This is recommended, however, for short tasks. If you plan running this task for a longer period of time, AsyncTask is probably not a good choice.
  • You can run a background Service with a Handler to update the UI. Depends on what you're trying to achieve.
  • You'll probably want to have a look at ScheduledExecutorService. It has a method called scheduleAtFixedRate() which will do exactly that, execute a Runnable each X time specified by one of the parameters. More info here.
nKn
  • 13,691
  • 9
  • 45
  • 62
  • Thank you for the answer. I should've clarified. By postDelayed, I meant calling itself every x amount of second. One thing I didn't understand, what do you mean by "having a thread won't free up resources". When you call thread.sleep, it gives the UI thread and other threads chance to do their work. I like your last option, except it seems that it does not execute on UI thread so I have to also post it to UI thread – Snake Jan 21 '15 at 18:14
  • The control is indeed given to the UI thread, but you still have that `Thread` loaded into memory, so it's not freed up but waiting until next execution. This shouldn't be an issue, however, but you asked about efficiency so I just noted that. For the UI issue, have a look at this, it might be helpful: http://stackoverflow.com/questions/6700802/android-timer-updating-a-textview-ui – nKn Jan 21 '15 at 18:21