Can someone provide an example as to how to use the proximity sensor? I tried to us开发者_高级运维e it the same way as other sensors, but it's not working.
This is the code snippet i have been using:
final SensorManager mSensorManager;
final Sensor mproximity;
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mproximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
mSensorManager.registerListener(new SensorListener(){
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
Toast.makeText(test.this,"proximity sensor accu ", Toast.LENGTH_SHORT).show();
}
public void onSensorChanged(int arg0, float[] arg1) {
// TODO Auto-generated method stub
Toast.makeText(test.this,"proximity sensor ", Toast.LENGTH_SHORT).show();
}
}, Sensor.TYPE_PROXIMITY, 1);
Please tell me where I am going wrong.
The method registerListener(SensorListener, int, int)
is deprecated, use registerListener(SensorEventListener, Sensor, int)
instead:
mSensorManager.registerListener(proximityListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
SensorManager.SENSOR_DELAY_UI);
Furthermore you should save a reference to your Sensor(Event)Listener
, to be able to unregister it.
Gubbel makes a valid point. Please use the latest API.
Also do note that the proximity sensor is implemented differently from
the other sensors. While the other sensors can be "polled" the
proximity sensor is interrupt based.
So you get a onSensorChanged event ONLY when a proximity state
transition occurs (ie near-to-far or far-to-near).
Often the proximity sensor is implemented using the light-sensor hardware.
So, you can launch your app and cover/uncover the light-sensor on the top
of your device. Doing so will trigger the proximity-sensor transitions
and you will surely get data (0/1 or far/near) in your app then.
More info on Proximity sensor on Android.
精彩评论