Question

I am beginner to android , I have problem in the following example to print gyroscope values using 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]);

}

}

Code is not working .Any example ,tutorial would also be helpful .Thanks in advance.

Was it helpful?

Solution

Here is a good example, read this all you need is inside..

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

Also, its better to check if this sensor is available on your hardware, for example:

    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;
         }
      }

If sensor not available, give some Toast to show the user that this will not work with the device. For example in your 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();

       } 
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top