0

I'm trying to run a piece of code periodically every 3 seconds that can change the color of a button.

So far I have:

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(2);

// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
    public void run() {

        queryFeedback2(); // display the data
    }
}, 0, 3, TimeUnit.SECONDS);

This code will run the piece of code but will not update my UI with the results.

Firstly, what code be cause my UI updating issues?

And secondly, is this the way I should be running my code periodically? Is there a better way?

Miguel
  • 1,157
  • 1
  • 15
  • 28

1 Answers1

0

Yes, there are few options available.

  1. Thread
  2. Runnable
  3. TimerTask

As stated by alex2k8 in their answer here:

final Runnable r = new Runnable()
{
    public void run() 
    {
        tv.append("Hello World");
        handler.postDelayed(this, 1000);
    }
};

handler.postDelayed(r, 1000);

Or we can use normal thread for example (with original Runner):

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                handler.post(r);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();

You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.

More details are here http://developer.android.com/reference/android/os/Handler.html

You can update the UI from handler. Tutorial for using handler, thread is available here.

Selecting between above mentioned option is really based on what kind of functionality you need. If you only need to do something at few interval then any of the above should be fine.

Community
  • 1
  • 1
VendettaDroid
  • 3,131
  • 2
  • 28
  • 41