参考文章:https://blog.csdn.net/hello_1995/article/details/119890052
原文章写的很详细,但是没有获取气压计数据的片段,本人按原代码改写了一份
本人新手一枚,第一次发文章,不是很懂,希望大家多多提意见
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private final String TAG = "sensor-sample";
private TextView tv_baro;
private TextView tv_acc;
private SensorManager mSensorManager;
private MySensorEventListener mMySensorEventListener;
private float mPressure = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_baro = findViewById(R.id.tv_barometer_value);
tv_acc = findViewById(R.id.tv_accuracy);
this.mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
this.mMySensorEventListener = new MySensorEventListener();
}
@Override
protected void onResume() {
super.onResume();
if (mSensorManager == null) {
return;
}
Sensor barometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if (barometerSensor != null) {
//register accelerometer sensor listener
mSensorManager.registerListener(mMySensorEventListener, barometerSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Log.d(TAG, "Barometer Sensors are not supported on current devices.");
}
}
@Override
protected void onPause() {
super.onPause();
if (mSensorManager == null) {
return;
}
//unregister all listener
mSensorManager.unregisterListener(mMySensorEventListener);
}
private class MySensorEventListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
mPressure = event.values[0];
tv_baro.setText(String.valueOf(mPressure));
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
switch (accuracy) {
case 0:
tv_acc.setText("acc:"+"Unreliable");
case 1:
tv_acc.setText("acc:"+"Low Accuracy");
case 2:
tv_acc.setText("acc:"+"Medium Accuracy");
case 3:
tv_acc.setText("acc:"+"High Accuracy");
}
}
}
}