Android getDefaultSensor无法解决错误

时间:2012-11-06 10:11:13

标签: android sensor

我正在尝试制作一个使用板载加速度计的应用程序。

当我设置我的传感器时,我在使用TYPE_MAGNETIC_FIELD时收到错误消息,它说:TYPE_MAGNETIC_FIELD无法解析为变量。 TYPE_ACCELERATOR很好,很好。

这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sensor);

    sensMan = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    magFieldSens = sensMan.getDefaultSensor(TYPE_MAGNETIC_FIELD);
    accelerometer = sensMan.getDefaultSensor(TYPE_ACCELEROMETER);

    sensListen = new MySensorEventListener();

    orientationView = (TextView) findViewById(R.id.orientationView);


}

这些是在我的主要活动中定义的:

SensorManager sensMan;
Sensor accelerometer, magFieldSens;
SensorEventListener sensListen;
    TextView orientationView;

在这个类中,TYPE_MAGNETIC_FIELD可以按预期使用:

    class MySensorEventListener implements SensorEventListener
{



    /* 
     * @see android.hardware.SensorEventListener#onAccuracyChanged(android.hardware.Sensor, int)
     */
    @Override
    public void onAccuracyChanged(Sensor sensor, int acc)
    {
        // Edit this method, macke
        if(acc <= 1)
            Toast.makeText(SensorActivity.this, "Shake in a figure eight pattern ", Toast.LENGTH_LONG).show();


    }


    @Override
    public void onSensorChanged(SensorEvent sensorEvent)
    {
        int sensorEventType = sensorEvent.sensor.getType();

        if (sensorEventType == Sensor.TYPE_ACCELEROMETER)
            System.arraycopy(sensorEvent.values, 0, gravVals, 0, 3);

        else if(sensorEventType == Sensor.TYPE_MAGNETIC_FIELD)
            System.arraycopy(sensorEvent.values, 0, geoMagnetVals, 0, 3);
        else
            return;

        if(SensorManager.getRotationMatrix(rotMatrix, null, gravVals, geoMagnetVals))
        {
            SensorManager.getOrientation(rotMatrix, orientation);
            orientationView.setText("X: " + orientation[0] + 
                                    "\nY: " + orientation[1] + 
                                    "\nZ: " + orientation[2]);


        }


    }



}

干杯 / M

1 个答案:

答案 0 :(得分:0)

你可以写

  magFieldSens = sensMan.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

TYPE_MAGNETIC_FIELD 是传感器的静态常量整数。