Android: Which thread calls .onSensorChanged?

时光毁灭记忆、已成空白 提交于 2019-11-30 04:56:38

问题


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!


回答1:


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().



来源:https://stackoverflow.com/questions/17681870/android-which-thread-calls-onsensorchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!