在onCreate 得到SensorManger实例
private SensorManager sensorManager = null;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
onResume()要注册监听器
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
}
onPause()要注销监听器
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
实现监听返回结果的接口SensorEventListener
public class MainActivity extends Activity implements SensorEventListener {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
// 获取绕Z轴转过的角度
float tmp = event.values[0];
Animation rotateAnimation = new RotateAnimation(angle, -tmp, directionTextView.getWidth() >> 1 ,directionTextView.getHeight() >> 1 );
rotateAnimation.setDuration(100);
rotateAnimation.setFillAfter(true);//动画之后就保持动画结束的位置
directionTextView.startAnimation(rotateAnimation);
angle =-tmp;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
要旋转的图片