2

How can I use a ScheduledThreadPoolExecutor and schedule a task which is always executed on the UI thread?

Currently, I do the following

    mScheduledTask = sBackgroundExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            if (mActivity != null) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // do UI stuff
                    }
                });
            }
        }
    }, 0, 200, TimeUnit.MILLISECONDS);

This seems unnecessary and hard to read, but I couldn't find anything in the docs. Is it possible or is this the only way?

Mahoni
  • 7,088
  • 17
  • 58
  • 115
  • 1
    use a Handler and its postDelayed method – Blackbelt Mar 16 '15 at 13:58
  • 1
    Agreed. See [this sample project](https://github.com/commonsguy/cw-omnibus/tree/master/Threads/PostDelayed). – CommonsWare Mar 16 '15 at 13:59
  • @CommonsWare is it bad to use `Thread.sleep()` instead of handler with postDelayed? – Apurva Mar 16 '15 at 14:04
  • 1
    @Apurva: Please do not use `Thread.sleep()` on the main application thread. `postDelayed()` will be more efficient than anything that uses a background thread (e.g., `Timer`, `ScheduledExecutorService`), as it does not require an additional thread, and you then *still* have to do something to get your work done on the main application thread. – CommonsWare Mar 16 '15 at 14:06

0 Answers0