3

I use ScrollView class in my application. I draw some data on canvas from the compass, these data are periodically updated by user's interaction.

How can I periodically call onDraw method without user's touch on the display? Can I periodically refresh content of the canvas without other thread and calling view.postInvalidate()?

misco
  • 1,912
  • 4
  • 41
  • 68
  • 1
    Why wouldn't you want to use another thread to do this? – DRiFTy Mar 15 '12 at 20:13
  • I think that there is other way. If there isn't another way, I use thread... – misco Mar 15 '12 at 20:27
  • The only way that I can see this happening is with a thread, the answer by DeeV below is what you should do. The Handler will allow you to make a call from your own thread to the UI thread. – DRiFTy Mar 15 '12 at 20:34
  • thanks, I applied DeeV answer on it and it is fixed. – misco Mar 15 '12 at 20:47
  • I just noticed this. The Handler runs on the UI thread. It's not its own thread like may be inferred here. – DeeV Jun 26 '12 at 11:28

1 Answers1

9

The Handler class is very handy for things like this.

Handler viewHandler = new Handler();
Runnable updateView = new Runnable(){
  @Override
  public void run(){
     globalView.invalidate();
     viewHandler.postDelayed(updateView, MILLISECONDS_TILL_UPDATE);
  }
};

Call viewHandler.post(updateView); anywhere in the UI thread and it will infinitely call that Runnable every x number of milliseconds specified in MILLISECONDS_TILL_UPDATE. Call viewHandler.removeCallbacks(updateView); to end it or use a boolean flag to prevent another post.

biddulph.r
  • 5,226
  • 3
  • 32
  • 47
DeeV
  • 35,865
  • 9
  • 108
  • 95