2
我在java(Android)中實現了一個類來計算設備的高度,我想從另一個類訪問此值。傳感器的返回值總是爲0
第一類是如下:
public class DeviceAltitudeHandler extends Activity implements SensorEventListener{
SensorManager sm;
Sensor sensor;
float altitude ;
public DeviceAltitudeHandler(SensorManager sm, float altitude) {
super();
this.sm = sm;
this.altitude = altitude;
sensor = sm.getDefaultSensor(Sensor.TYPE_PRESSURE);
sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
}
@Override
public void onSensorChanged(SensorEvent event) {
float [] values = event.values;
altitude = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE,values[0]);
}
public float getAltitude() {
return altitude;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void start() {
sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
}
public void stop() {
sm.unregisterListener(this);
}
}
我使用的是集成的晴雨表,但返回的值始終爲0真正的智能手機!和所述第二類的代碼是:預先
public class TestActivity extends Activity {
TextView tv;
DeviceAltitudeHandler dah;
float altitude;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
tv = (TextView) findViewById(R.id.textView5);
SensorManager sm = (SensorManager) getSystemService(Service.SENSOR_SERVICE);
dah = new DeviceAltitudeHandler(sm,altitude);
tv.setText(""+dah.getAltitude());
}
@Override
protected void onResume() {
super.onResume();
dah.start();
}
@Override
protected void onPause() {
super.onPause();
dah.stop();
}
}
感謝。
感謝您的快速回復。問題出在onSensorChanged方法,沒有調用,並且返回值始終爲0(初始值)。 – Wima
事實上,問題出在「getAltitude()」方法,它不會返回高度值。 – Wima
@Wima你可以檢查這個鏈接http://stackoverflow.com/questions/7410095/android-is-there-a-way-to-obtain-altitude-aside-from-location-getaltitude-i並與你的代碼進行比較也許你犯了一些錯誤 –