How to execute background job that update UI view

2019-05-11 06:39发布

In my Android application I have an activity with views.

To the beginning of the activity or to the creation of main layout for example, I would like to start a background job that goes to update UI view from main layout for each 5 seconds.

So, my strategy for the moment was to create Runnable during creation of the main layout by using runOnUiThread method of my class that derives from View.

The thread starts correctly but in the thread I would like to do a wait for 5 seconds to wait before update UI view again. My problem is when I use Thread.sleep, the UI is blocked.

I guess Thread.sleep() blocks the entire UI but I don't know how I must make to solve that problem.

So my question is the following : what is the best solution to realize what I want (without using sleep perhaps) ?

3条回答
Lonely孤独者°
2楼-- · 2019-05-11 07:33

The following link has the answer for all your doubts:

Android Painless Threading

查看更多
地球回转人心会变
3楼-- · 2019-05-11 07:39

Also consider using an AsyncTask with a Timer. You don't have to worry about handlers this way

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-05-11 07:44

You can use a Timer to schedule a repeating TimerTask. Each time you wanted to update the UI, you can post to a Handler that you previously created in the UI thread.

Just remember to cancel your Timer in onPause and create a new Timer in onResume.

查看更多
登录 后发表回答