Not able to get proximity sensor's values in android
Asked Answered
C

2

5

Can someone provide an example as to how to use the proximity sensor? I tried to use 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.

Contuse answered 9/12, 2010 at 21:28 Comment(0)
S
5

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.

Skivvy answered 21/2, 2011 at 22:52 Comment(0)
P
2

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.

Pegeen answered 5/3, 2011 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.