简体   繁体   English

如何在Android编程中使用接近传感器

[英]How to use Proximity Sensor in Android Programming

I know that there are only two values of proximity : 0.0 & 1.0 我知道只有两个接近值: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 我需要一个简单的代码来检测通过设备的传感器的接近度,并在接近度变为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. 您可以使用getMaximumRange()方法获取接近传感器的最大范围,并使用它来确定要执行的操作。

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. 现在使用maxRange做你想做的事。

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. 它并不总是报告1.0和0.0。 For example my Moto G (1st Gen.) reports 3 cm as its min range and 100 cm as its max range. 例如我的Moto G(第1代)报告其最小范围为3厘米,最大范围为100厘米。 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. 因此,最好获取设备传感器的最大范围,并在代码中使用它,而不是对值进行硬编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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