0

抱歉这个愚蠢的问题,但我是 android 新手,我找不到解决方案。

简而言之,我有一个带有 sensoreventlistener 的类,我想在主要活动中使用从传感器接收到的数据。我试过但没有成功这是我的代码:

public class Lis{

SensorManager MagSensorManager;
SensorManager ACCSensorManager;
Sensor magnetometer;
Sensor Accelerometer;
Callback cb =null;
float [] magvec =new float[3];
float [] lin =new float[3];





Lis(Context context, Callback cb)
{

    MagSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    ACCSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

    ACCSensorManager.registerListener(listener,Accelerometer, SensorManager.SENSOR_DELAY_GAME);
    MagSensorManager.registerListener(listener,magnetometer, SensorManager.SENSOR_DELAY_GAME);
    this.cb=cb;
}
SensorEventListener listener = new SensorEventListener() {

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}
public void onSensorChanged(SensorEvent event) {

    switch (event.sensor.getType())
    {
    case Sensor.TYPE_MAGNETIC_FIELD:
         magvec = event.values.clone();
         break;
    case Sensor.TYPE_LINEAR_ACCELERATION:
         lin = event.values.clone();
         break;

    }



            SensorManager.getRotationMatrix(Ri, I, lin, magnetic);
        SensorManager.getOrientation(Ri, orientat);
                orientat[0] = (float) Math.toDegrees(orientat[0]);
            cb.azvalue(orientat[0]);

}
}

};



 public interface Callback {
        void azvalue(float azim);

    }

}


公共类 MainActivity 扩展 Activity 实现 Lis.Callback{

    TextView tbX;

    Lis listen;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tbX = (TextView)findViewById(R.id.textView1);
        listen=new Lis(this,this);
    }       


    @Override
    protected void onPause() {
        super.onPause();

    }
    public void azvalue(float azim)
    {
        tbX.setText("azimuth"+azim);
    }

}

我哪里错了?如果我尝试运行 apk,我只会从 tbX textview 获得默认文本,而不是“方位角”+值。

提前致谢。

4

1 回答 1

0
SensorManager MagSensorManager;
SensorManager ACCSensorManager;  

您只需要一个 SensorManager

SensorManager mSensorManager;  

在构造函数中

Lis(Context context, Callback cb)
{

    mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

    // You need to initialize these value, otherwise you pass in null 
    // and onSensorChanged would not be called as in your case.
    magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    Accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    mSensorManager.registerListener(listener,Accelerometer, SensorManager.SENSOR_DELAY_GAME);
    mSensorManager.registerListener(listener,magnetometer, SensorManager.SENSOR_DELAY_GAME);
    this.cb=cb;
}
于 2013-05-01T19:42:27.340 回答