Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Which thread calls .onSensorChanged?

I've read a few discussions about which thread calls various callback methods, for example those associated with Sensors. Most claim that the UI thread calls the callbacks - even when a separate worker thread is involved. Are we CERTAIN about that?

Consider this scenario: A separate class implements Runnable and SensorListener. The UI thread (during onCreate) starts the runnable and then goes back to its other business. The now-independent worker thread, in its own class, then registers the SensorListener.

Note that the UI thread never has any interaction with SensorManager nor SensorListener. The only thread that ever touches anything to do with Sensor, and the only class and member methods that it ever knows about, is the worker thread and its class.

It's hard for me to imagine that the UI thread would be calling the callback in this situation. Yet the online discussions are pretty "confident". Anyone know for certain?

Thanks!

like image 329
AndroidNewbie Avatar asked Jul 16 '13 16:07

AndroidNewbie


1 Answers

Are we CERTAIN about that?

Yes, though it depends on how you register the listener, and the behavior is not especially well-documented.

There are two registerListener() methods that take a SensorEventListener. One takes a Handler, the other does not. The latter one will use a Handler that is associated with the main application thread. If you wish to have the events delivered to a background thread, use a HandlerThread (which really should be called LooperThread, but they didn't ask me...), create a Handler in it, and use that Handler with registerListener().

like image 131
CommonsWare Avatar answered Oct 15 '22 03:10

CommonsWare