0

我是 android 的初学者,在以下示例中使用 android 打印陀螺仪值时遇到问题。

public class Gyro extends Activity implements OnClickListener,SensorEventListener {

   Button click;

   SensorManager sm;

   Sensor gyroscope; 

   int decide=1;

   Context c;

   TextView txt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_gyro);

    c = getApplicationContext();

click = (Button)findViewById(R.id.btnAction);

sm = (SensorManager)getSystemService(SENSOR_SERVICE);

gyroscope = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);

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

click.setText("Start");
click.setOnClickListener(this);
}

@Override
public void onClick(View arg0) {

    if(decide==1)
    {
        sm.registerListener(Gyro.this,gyroscope,SensorManager.SENSOR_DELAY_NORMAL);

        click.setText("Stop");
        decide=0;

    }else if(decide==0){

        sm.unregisterListener(Accelerometer.this);

        click.setText("Start");
        decide=1;
    }
}

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

}

@Override
public void onSensorChanged(SensorEvent event) {

    txt.setText(event.values[0]+"::"+event.values[1]+"::"+event.values[2]);

}

}

代码不起作用。任何示例,教程也会有所帮助。提前致谢。

4

1 回答 1

1

这是一个很好的例子,阅读这个你所需要的就在里面..

http://www.41post.com/3745/programming/android-accessing-the-gyroscope-sensor-for-simple-applications

此外,最好检查此传感器是否在您的硬件上可用,例如:

    Boolean sensorAvailable = false;
    List<Sensor> sensorList = sm.getSensorList(Sensor.TYPE_ALL);
    for(int i=0;i<sensorList.size();i++){

         if(sensorList.get(i)==Sensor.TYPE_GYROSCOPE){
           sensorAvailable=true;
         }
      }

如果传感器不可用,请给一些 Toast 以向用户表明这不适用于设备。例如在您的 onClick 中:

         @Override
      public void onClick(View arg0) {

    if(sensorAvailable==true){
     if(decide==1)
         {
          sm.registerListener(Gyro.this,gyroscope,SensorManager.SENSOR_DELAY_NORMAL);

          click.setText("Stop");
         decide=0;

      }else if(decide==0){

          sm.unregisterListener(Accelerometer.this);

         click.setText("Start");
           decide=1;
       }else{


       Toast.makeText(Gyro.this,"Gyroscope not available",Toast.LENGTH_LONG).show();

       } 
    }
于 2013-05-27T11:26:07.420 回答