0

I'd like to use handler.postDelayed instead of Thread.sleep() in a loop. Basically I have a sequence of numbers in a string and for each number I need a different delay to do an specific action.

hThread = new HandlerThread("HandlerThread");

    seqRunnable = new Runnable() {
        @Override
        public void run() {

            for (int i = 0; i < seq.length() ; i++) {

                    if (seq.charAt(i) == '0') {
                        Log.d(TAG, "seqCode: 0");

                        try {
                            Thread.sleep(1200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    if (seq.charAt(i) == '1') {
                        Log.d(TAG, "seqCode: 1");

                        try {
                            Thread.sleep(400);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (seq.charAt(i) == '2') {
                        Log.d(TAG, "seqCode: 2");

                        try {
                            Thread.sleep(1200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }

                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


            }

            if (hThread != null && hThread.isAlive())
                seqHandler.postDelayed(seqRunnable, 2400);
            Log.d(TAG, "seqCode done!");
        }
    };

While using Thread.sleep() works, I guess using a handler.postDelayed() is the preferred way but the timings when I use it are all wrong.

Any help would be much appreciated.

0 Answers0