我需要每秒自动刷新我的Activity中显示的数据,我已经使用了runnable,计时器等。这些工作完美但几秒后UI很慢,有时没有响应。我读过IntentService
,但我不认为在IntentService
中使用无限循环是个好主意。有什么我想念的,请帮助。
答案 0 :(得分:1)
我会做这样的事情。
private Handler mRepeatHandler;
private Runnable mRepeatRunnable;
private final static int UPDATE_INTERVAL = 5000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRepeatHandler = new Handler();
mRepeatRunnable = new Runnable() {
@Override
public void run() {
//Do something awesome
mRepeatHandler.postDelayed(mRepeatRunnable, UPDATE_INTERVAL);
};
mRepeatHandler.postDelayed(mRepeatRunnable, UPDATE_INTERVAL);
}
@Override
protected void onDestroy() {
super.onDestroy();
mRepeatHandler.removeCallbacks(mRepeatRunnable);
}
答案 1 :(得分:0)
也许这可能会有所帮助:
private class WaitTimer extends TimerTask {
@Override
public void run() {
//every 5 seconds
if(millis % 5 == 0) {
//Do your magic here
}
millis+=1
}
}
然后在onCreate()
millis = 0;
timer = new Timer();
timer.schedule(new WaitTimer(), 0, 1000);