问题
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