开发者

Android: Scheduled Job & CPU efficiency

开发者 https://www.devze.com 2023-02-16 09:27 出处:网络
In my application I need to pull data from server approximately each 3 minutes, to do this app starts new thread when it shows particular activity and then this thread just pulls data then sleep then

In my application I need to pull data from server approximately each 3 minutes, to do this app starts new thread when it shows particular activity and then this thread just pulls data then sleep then pull etc... But I've found that this is not so efficient for CPU usage, so my question is:

What is the 开发者_高级运维best solution in terms of CPU usage to do background periodic data pull from server. Should it be AlarmManager, Thread or some other technique.


If the data-pulling is done only when the activity is in an active state, you should use the handler mechanism to schedule periodic tasks from the UI thread, as suggested here: http://developer.android.com/resources/articles/timed-ui-updates.html it's all based around this functions:

mHandler.postDelayed(mUpdateTimeTask, 100);

where mHandler is your handler, and mUpdateTimeTask is a Runnable containing the action to be performed after the given period of time (100 ms, in the example). Pay attention that mUpdateTimeTask is execute in the UI thread, so you have to initialize and start your own thread. To simplyfy this task, Android offers AsyncTask: http://developer.android.com/resources/articles/painless-threading.html

0

精彩评论

暂无评论...
验证码 换一张
取 消