Java – Best Way to Repeat Background Threads in Android?

Best Way to Repeat Background Threads in Android?… here is a solution to the problem.

Best Way to Repeat Background Threads in Android?

I need to constantly read data from USB (at least 50 milliseconds apart) and update multiple views at the same time.

Updating a View can be easily achieved by using a handler, but since USB reading does too much work and doesn’t need to touch the UI thread, it must be done on a different thread.

I looked at a couple of questions< a href="https://stackoverflow.com/questions/6531950/how-to-execute-async-task-repeatedly-after-fixed-time-intervals" rel="noreferrer noopener nofollow" > Like this about repeating AsyncTask but correct me if I’m wrong: this doesn’t seem like a good approach.

What is the best way to repeat background work in Android?

Solution

If you need more fine-grained control over the elapsed time, I recommend starting a separate thread with loops and using it Thread.sleep waits before polling. When you have something new, dispatch it along with the handler to the UI thread.

Something like this (rough sketch, should give you an idea):

    new Thread() {
        private boolean stop = false;

@Override public void run() {
            while (!stop) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                 poll the USB and dispatch changes to the views with a Handler
            }
        }

public void doStop() {
            stop = true;
        }
    };

Related Problems and Solutions