package com.tang.sensor; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.os.Build; public class MainActivity extends Activity { private Mylister listener; private SensorManager sm; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = (ImageView) findViewById(R.id.iv); sm = (SensorManager) getSystemService(SENSOR_SERVICE); Sensor ss = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);//方向傳感器 listener = new Mylister(); sm.registerListener(listener, ss, SensorManager.SENSOR_DELAY_UI); } private class Mylister implements SensorEventListener { //精度改變 public void onAccuracyChanged(Sensor sensor, int accuracy) { } //傳感器數據變化時 public void onSensorChanged(SensorEvent event) { float[] values = event.values; float angle = values[0]; System.out.println(angle); //能夠旋轉指南針圖片 RotateAnimation ra = new RotateAnimation(0, angle, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); ra.setDuration(100); iv.startAnimation(ra); } } @Override protected void onDestroy() { sm.unregisterListener(listener); listener = null; super.onDestroy(); } }