Android:哪个线程调用 .onSensorChanged? [英] Android: Which thread calls .onSensorChanged?

查看:36
本文介绍了Android:哪个线程调用 .onSensorChanged?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些关于哪个线程调用各种回调方法的讨论,例如与传感器相关的那些.大多数人声称 UI 线程调用回调 - 即使涉及单独的工作线程.我们对此有把握吗?

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?

考虑这种情况:一个单独的类实现了 Runnable 和 SensorListener.UI 线程(在 onCreate 期间)启动可运行对象,然后返回到它的其他业务.现在独立的工作线程在它自己的类中注册 SensorListener.

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.

请注意,UI 线程从不与 SensorManager 或 SensorListener 进行任何交互.唯一与 Sensor 有任何关系的线程,以及它所知道的唯一类和成员方法,就是工作线程及其类.

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.

我很难想象 UI 线程会在这种情况下调用回调.然而网上的讨论却相当自信".有人确切知道吗?

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?

谢谢!

推荐答案

我们对此有把握吗?

Are we CERTAIN about that?

是的,尽管这取决于您注册侦听器的方式,并且行为没有特别详细的记录.

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

有两个 registerListener() 方法接受一个 SensorEventListener.一个需要一个 Handler,另一个没有.后者将使用与主应用程序线程相关联的 Handler.如果您希望将事件传递到后台线程,请使用 HandlerThread(实际上应该称为 LooperThread,但他们没有问我...),在其中创建一个 Handler,并将该 HandlerregisterListener() 一起使用.

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

这篇关于Android:哪个线程调用 .onSensorChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆