Best way to replay background thread in Android?

I need to constantly read data from USB (50ms minimum) and update several at the same time View

.

Updating View

can be achieved quite easily with Handler

, but since USB reading is too much work and there is no need to touch the UI thread, it must be done on a different thread.

I have read a couple of questions about execution several times AsyncTask

, but please correct me if I am wrong: it seems like this is not a good way to go.

What are the best ways to re-do background work in Android?

+3


source to share


1 answer


If you need finer control over the elapsed time, I suggest you start a separate thread with a loop and use Thread.sleep to wait before polling. When you have something new, send it to the handler on 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;
        }
    };

      

+3


source







All Articles