ANDROID_MARS学习笔记_S05_005_方向传感器
1 import android.app.Activity; 2 import android.content.Context; 3 import android.hardware.Sensor; 4 import android.hardware.SensorEvent; 5 import android.hardware.SensorEventListener; 6 import android.hardware.SensorManager; 7 import android.os.Bundle; 8 9 public class MainActivity extends Activity implements SensorEventListener{ 10 private SensorManager mSensorManager; 11 private Sensor mOrientation; 12 13 @Override 14 public void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 18 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 19 mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); 20 } 21 22 @Override 23 public void onAccuracyChanged(Sensor sensor, int accuracy) { 24 // Do something here if sensor accuracy changes. 25 // You must implement this callback in your code. 26 } 27 28 @Override 29 protected void onResume() { 30 super.onResume(); 31 mSensorManager.registerListener(this, mOrientation, SensorManager.SENSOR_DELAY_NORMAL); 32 } 33 34 @Override 35 protected void onPause() { 36 super.onPause(); 37 mSensorManager.unregisterListener(this); 38 } 39 40 @Override 41 public void onSensorChanged(SensorEvent event) { 42 float azimuth_angle = event.values[0]; 43 float pitch_angle = event.values[1]; 44 float roll_angle = event.values[2]; 45 46 System.out.println("azimuth--->" + azimuth_angle); 47 System.out.println("pitch_angle--->" + pitch_angle); 48 System.out.println("roll_angle--->" + roll_angle); 49 // Do something with these orientation angles. 50 } 51 }
You can do anything you set your mind to, man!