I'm confused by Handler
and HandlerThread
classes usage. The reason I'm trying to use them is I want to utilize AudioRecord
class and its setRecordPositionUpdateListener
method (reference). The methos description says:
Use this method to receive AudioRecord events in the Handler associated with another thread than the one in which you created the AudioTrack instance.
And that's exactly what I want - to setup the AudioRecord
in the main thread, but receive data in a working thread. I figure I need a HandlerThread
so I've created and started one. I've also defined a callback method that implements AudioRecord.OnRecordPositionUpdateListener
interface. I want this callback to be called from the worker HandlerThread
. What I don't understand now is how to create the Handler
to pass to setRecordPositionUpdateListener
.
To associate Handler
with a certain thread, you should create it by passing corresponding Looper
in its constructor. So, if you already have a HandlerThread
it can be done in the following way:
Looper looper = myHandlerThread.getLooper();
Handler handler = new Handler(looper);
And that's it, just use this handler in setRecordPositionUpdateListener
method and callback will be executed at the worker thread. If you need more explanation on Handler
, Looper
and HandlerThread
, you can take a look here.