2

我需要每秒自动刷新 Activity 中显示的数据,我使用了 runnable、timer 等。这些工作完美,但几秒钟后 UI 很慢,有时没有响应。我已经阅读过,IntentService但我认为在IntentService. 有什么我错过的,请帮忙。

4

2 回答 2

2

我会做这样的事情。

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);
}
于 2016-08-24T18:30:38.030 回答
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);
于 2016-08-23T20:10:46.310 回答