android 测距仪源代码
时间: 2023-07-28 08:04:31 浏览: 62
Android测距仪是一种应用程序,用于测量物体与设备之间的距离。以下是一个示例的Android测距仪源代码:
```java
public class DistanceMeasurer extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor proximitySensor;
private TextView distanceTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
distanceTextView = findViewById(R.id.distance_textview);
if (proximitySensor == null) {
Toast.makeText(this, "该设备不支持近距离传感器", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
protected void onStart() {
super.onStart();
sensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
super.onStop();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
float distance = event.values[0];
distanceTextView.setText(String.format("距离:%f cm", distance));
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// 不需要实现,但是必须存在
}
}
```
这段代码创建了一个名为`DistanceMeasurer`的Activity类,它实现了`SensorEventListener`接口,用于监听近距离传感器的数据变化。在`onCreate`方法中,我们获取了传感器管理器的实例,并通过`getDefaultSensor`方法获取了近距离传感器。在`onStart`方法中,我们注册了传感器监听器。在`onStop`方法中,我们取消了传感器监听器的注册。
`onSensorChanged`方法会在传感器数值发生变化时调用,并将距离值显示在`TextView`上。`onAccuracyChanged`方法在传感器精度变化时调用,但在这个例子中我们没有实现它。
请注意,为了使这个应用程序正常工作,您还需要在布局文件中添加一个`TextView`(id为`distance_textview`),用于显示测量距离。
希望这段代码对你有帮助!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)