简体   繁体   中英

How to use Proximity Sensor in Android Programming

I know that there are only two values of proximity : 0.0 & 1.0

I need a simple code to detect proximity through the device's sensors, and perform any task if proximity changes to 1.0

this is what i found.

public class SensorActivity extends Activity implements SensorEventListener {
 private SensorManager mSensorManager;
 private Sensor mSensor;
 ImageView iv;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.sensor_screen);
  mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
  iv = (ImageView) findViewById(R.id.imageView1);
 }

 protected void onResume() {
  super.onResume();
  mSensorManager.registerListener(this, mSensor,
    SensorManager.SENSOR_DELAY_NORMAL);
 }

 protected void onPause() {
  super.onPause();
  mSensorManager.unregisterListener(this);
 }

 public void onAccuracyChanged(Sensor sensor, int accuracy) {
 }

 public void onSensorChanged(SensorEvent event) {
  if (event.values[0] == 0) {
   iv.setImageResource(R.drawable.near);
  } else {
   iv.setImageResource(R.drawable.far);
  }
 }
}

You can use the getMaximumRange() method to obtain your proximity sensor's max range and use it to determine what to do.

SensorManager sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
float maxRange = proximitySensor.getMaximumRange();

Now use maxRange to do what you want to do.

public void onSensorChanged(SensorEvent event) {
if(maxRange == event.values[0]) {
// Do something when something is far away.
}
else {
// Do something when something is near.
}
}

One very important thing. The proximity sensor varies from device to device. It not always reports 1.0 and 0.0. For example my Moto G (1st Gen.) reports 3 cm as its min range and 100 cm as its max range. So its best to obtain the max range of the device's sensor and use it in your code rather then hard-coding the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM