SensorManager.registerListener (.., Handler handler), example please?

拥有回忆 提交于 2020-01-01 03:21:08

问题


I don't understand how to use this method,

sensorManager.registerListener(SensorEventListener listener, Sensor sensor, int rate, Handler handler);

(Documentation here)

1) If it uses a SensorEventListener, then what's the purpose of the Handler?

2) Please give an example of a handler I could pass to it?

Thanks!


回答1:


If it uses a SensorEventListener, then what's the purpose of the Handler?

If I had to guess, it is so you can get your sensor events delivered on a background thread (e.g., a HandlerThread). By default, sensor events are delivered on the main application thread, which is fine in some cases.




回答2:


Here you have an example:

SensorManager mSensorMgr = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);

HandlerThread mHandlerThread = new HandlerThread("sensorThread");

mHandlerThread.start();

Handler handler = new Handler(mHandlerThread.getLooper());

mSensorMgr.registerListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_FASTEST, handler);

From the source code of android SensorManager's class you can see that the registerListener() extract the Looper of your Handler to create a new handler with this looper where it call the onSensorChanged method.

If you don't pass your handler,the SensorManager will use the main application thread.




回答3:


1) If it uses a SensorEventListener, then what's the purpose of the Handler? if you run it on the main thread , and you're doing some heavy calculations you will slow down the main UI to be unresponsive.Always write your long running tasks in a separate thread, to avoid ANR.

Here is an example http://stacktips.com/tutorials/android/android-service-example



来源:https://stackoverflow.com/questions/6069485/sensormanager-registerlistener-handler-handler-example-please

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