Android: Is there a way to obtain altitude aside from Location.getAltitude()? (I've heard using Sensor)

后端 未结 1 1672
说谎
说谎 2020-12-20 02:49

Is there a way to obtain altitude aside from Location.getAltitude()? I\'ve heard using Sensor but don\'t have idea and can\'t find on net.

UPDATES1

相关标签:
1条回答
  • 2020-12-20 03:21

    I know it's late but for anyone looking for it, that might help

    import android.app.Activity;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.os.Bundle;
    
    public class MyActivity extends Activity implements SensorEventListener {
    
        private SensorManager sensorManager;
        private Sensor sensor;
        private float altitude = 0;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
    
            if (sensor != null) 
                sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            sensorManager.unregisterListener(this);
        }
    
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    
        @Override
        public void onSensorChanged(SensorEvent event) {
            float presure = event.values[0];
            altitude = SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, presure);
    
            System.out.println("altitude => " + altitude);
        }
    }
    
    0 讨论(0)
提交回复
热议问题