我试图在Android的片段中制作指南针。 我在网上跟踪了一些课程并阅读了文档,但我收到了标题中所说的错误。
我的代码是:
public void onSensorChanged(SensorEvent event) {
final float alpha = 0.97f;
synchronized (this){
if(sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
mGravity[0] = alpha * mGravity[0] + (1 - alpha) * sensorEvent.values[0];
mGravity[1] = alpha * mGravity[1] + (1 - alpha) * sensorEvent.values[1];
mGravity[2] = alpha * mGravity[2] + (1 - alpha) * sensorEvent.values[2];
}
if(sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha) * sensorEvent.values[0];
mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha) * sensorEvent.values[1];
mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha) * sensorEvent.values[2];
}
float R[] = new float[9];
float I[] = new float[9];
boolean succes = SensorManager.getRotationMatrix(R,I, mGravity, mGeomagnetic);
if(succes){
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimuth = (float) Math.toDegrees(orientation[0]);
azimuth = (azimuth + 360) % 360;
Animation animation = new RotateAnimation(-correctAzimuth, azimuth, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
correctAzimuth = azimuth;
animation.setDuration(500);
animation.setFillAfter(true);
imageBoussole.startAnimation(animation);
}
}
}
在synchronized bloc中,androidEven无法识别sensorEven。 这是我的进口商品:
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
答案 0 :(得分:0)
代码中第一次出现sensorEvent
:
if(sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
sensorEvent
未在商家信息代码中的任何位置定义。 Android Studio不知道如何处理它并不奇怪。
您将参数命名为方法event
,而不是sensorEvent
:
public void onSensorChanged(SensorEvent event) {
所以,改为:
public void onSensorChanged(SensorEvent sensorEvent) {
或者,将对sensorEvent
的所有引用更改为event
。方法参数和您对该参数的使用需要匹配。