Tuesday, September 15, 2015

accelerometer

package com.example.accelerometer;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {
    //a TextView  
   private TextView tv;  
   //the Sensor Manager  
   private SensorManager sManager;  
 
   
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       
     //get the TextView from the layout file  
       tv = (TextView) findViewById(R.id.tv);  
 
       //get a hook to the sensor service  
       sManager = (SensorManager) getSystemService(SENSOR_SERVICE);  
       
       
       
       
   }
   
   protected void onResume()  
   {  
       super.onResume();  
       /*register the sensor listener to listen to the gyroscope sensor, use the
       callbacks defined in this class, and gather the sensor information as quick
       as possible*/  
       sManager.registerListener(this, sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_FASTEST);  
   }  
   
   
   
   protected void onStop()  
   {  
       //unregister the sensor listener  
       sManager.unregisterListener(this);  
       super.onStop();  
   }  
   
   
   public void onAccuracyChanged(Sensor arg0, int arg1)  
   {  
       //Do nothing.  
   }  
   
   
   public void onSensorChanged(SensorEvent event)  
   {  
       //if sensor is unreliable, return void  
       if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)  
       {  
           return;  
       }  
 
       //else it will output the Roll, Pitch and Yawn values  
       tv.setText("Orientation X (Roll) :"+ Float.toString(event.values[2]) +"\n"+  
                  "Orientation Y (Pitch) :"+ Float.toString(event.values[1]) +"\n"+  
                  "Orientation Z (Yaw) :"+ Float.toString(event.values[0]));  
   }  
   
   
   

   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.activity_main, menu);
       return true;
   }

   
}

No comments:

Post a Comment