我想获得设备的标题。为此,我使用了加速度计和磁力计传感器,并且实现了一个类。但是当我调用此类时,该类未返回任何值。 我是android开发的新手。请帮我。预先感谢。
我在主要活动中尝试了相同的代码,并且在主要活动中正在工作。
public Heading(Context context) {
this.context = context;
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
}
public void registerSensor() {
Sensor sensorAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(mSensorListener, sensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
Sensor sensorMagnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
sensorManager.registerListener(mSensorListener, sensorMagnetic, SensorManager.SENSOR_DELAY_NORMAL);
}
public final SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity = event.values;
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
mGeomagnetic = event.values;
}
heading = "event";
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
String getHeading() {
double azimuth = 0.0;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
if (SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic)) {
float[] orientation = new float[3];
SensorManager.getOrientation(R, orientation);
azimuth = orientation[0];
}
heading = String.valueOf((float)(Math.toDegrees(azimuth)+ 360) % 360);
}
return heading;
}
}
我需要设备的标题。