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!
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.
The android. hardware. Sensor class provides methods to get information of the sensor such as sensor name, sensor type, sensor resolution, sensor type etc.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With