-3

I am running a recursive handler which runs some code. I am posting the handler using a HandlerThread. I want to run the next recursive call only after the completion of the previous call. Is it possible to do so? If not what are the alternatives.

    HandlerThread ht = new HandlerThread();
    ht.start();
    Handler h = new Handler(ht.getLooper());
    h.post(new Runnable() {
         @override
         public void run(){
              //Some code
              h.postDelay(this,1000);
         }
    });
Naman Mehta
  • 26
  • 10

1 Answers1

1

Your code should work, but if you want a complete example how to run something recursively using HandlerThread, here it is:

public class Main2Activity extends AppCompatActivity {

    private MyWorkerThread mWorkerThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        mWorkerThread = new MyWorkerThread("myWorkerThread");
        final Runnable task = new Runnable() {
            @Override
            public void run() {
                Log.d("TAG", "Done.");
                mWorkerThread.postTask(this);
            }
        };
        mWorkerThread.start();
        mWorkerThread.prepareHandler();
        mWorkerThread.postTask(task);
    }

    @Override
    protected void onDestroy() {
        mWorkerThread.quit();
        super.onDestroy();
    }
}

class MyWorkerThread extends HandlerThread {

    private Handler mWorkerHandler;

    public MyWorkerThread(String name) {
        super(name);
    }

    public void postTask(Runnable task){
        mWorkerHandler.postDelayed(task, 1000); // set timeout which needed
    }

    public void prepareHandler(){
        mWorkerHandler = new Handler(getLooper());
    }
}

Don't forget to call handlerThread.quit() in onDestroy

Rainmaker
  • 10,294
  • 9
  • 54
  • 89
  • In this example the runnable will be executed after previous call is completed as you want. – Rainmaker Mar 22 '18 at 14:03
  • My bad. I didn't realise that the recursive is at the end. So it will be only be executed after the completion of the first one – Naman Mehta Mar 22 '18 at 14:22