Snake
Snake

Reputation: 14648

PostDelayed or Thread with thread.sleep()

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?

Upvotes: 1

Views: 1054

Answers (1)

nKn
nKn

Reputation: 13761

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.

Upvotes: 2

Related Questions