传感器简介

 

 

public class MainActivity extends Activity {

 private SensorManager sensorManager;

 private MyListener listener;

 private ImageView iv;

 private TextView tv;

 

 @SuppressWarnings("deprecation")

 @Override

 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

  this.iv = (ImageView) this.findViewById(R.id.iv);

  this.tv = (TextView) this.findViewById(R.id.tv);

 

  this.sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

  // 获取方向传感器

  Sensor sensor = this.sensorManager

    .getDefaultSensor(Sensor.TYPE_ORIENTATION);

  this.listener = new MyListener();

  this.sensorManager.registerListener(listener, sensor,

    SensorManager.SENSOR_DELAY_UI);

 }

 

 @Override

 protected void onDestroy() {

  this.sensorManager.unregisterListener(listener);

  super.onDestroy();

 }

 

 private class MyListener implements SensorEventListener {

  private float startAngle = 0f;

 

  @Override

  public void onAccuracyChanged(Sensor sensor, int accuracy) {

 

  }

 

  @Override

  public void onSensorChanged(SensorEvent event) {

   // values[0]: Azimuth, angle between the magnetic north direction

   // and the y-axis, around the z-axis (0 to 359). 0=North, 90=East,

   // 180=South, 270=West

   float angle = event.values [0];

   if(angle == 359 || angle == 0) {

    angle =0;

    startAngle = 0;

   }

   tv.setText("startAngle = "+ startAngle +", angle" +String.valueOf(angle));

   RotateAnimation animation = new RotateAnimation(startAngle, -angle,

     Animation.RELATIVE_TO_SELF, 0.5f,

     Animation.RELATIVE_TO_SELF, 0.5f);

   animation.setDuration(130);

   iv.startAnimation(animation);

   startAngle = -angle;

  }

 }

}

 

 

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:gravity="center" >

 

    <TextView

        android:id="@+id/tv"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="15dp"

        android:text="TextView" />

 

    <ImageView

        android:id="@+id/iv"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/textView1"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="48dp"

        android:src="@drawable/pointer" />

 

 

 

posted on 2013-10-25 19:10  Freedom000  阅读(123)  评论(0编辑  收藏  举报

导航