从非活动类获取数据实现sensoreventlistener

时间:2013-05-01 13:29:09

标签: android

对不起这个愚蠢的问题,但我是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获取默认文本而不是“方位角”+值。

提前致谢。

1 个答案:

答案 0 :(得分: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;
}