Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 852
CL22 Avatar asked May 20 '11 08:05

CL22


People also ask

What is SensorManager in android?

SensorManager lets you access the device's sensors . Always make sure to disable sensors you don't need, especially when your activity is paused. Failing to do so can drain the battery in just a few hours. Note that the system will not disable sensors automatically when the screen turns off.

Which class is used to make an occurrence of the sensor administration?

The android. hardware. Sensor class provides methods to get information of the sensor such as sensor name, sensor type, sensor resolution, sensor type etc.


3 Answers

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.

like image 63
markov00 Avatar answered Sep 21 '22 07:09

markov00


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.

like image 28
CommonsWare Avatar answered Sep 23 '22 07:09

CommonsWare


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

like image 24
ssk360 Avatar answered Sep 21 '22 07:09

ssk360