Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to get proximity sensor's values in android

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.

like image 570
chethan Avatar asked Dec 09 '10 21:12

chethan


2 Answers

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.

like image 163
Gubbel Avatar answered Oct 21 '22 13:10

Gubbel


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.

like image 24
TheCodeArtist Avatar answered Oct 21 '22 14:10

TheCodeArtist