Table of contents
Gyro sensor
1. Basic knowledge
Returns the angular acceleration data of the x, y, z axes.
Rotate horizontally counterclockwise, the z-axis is positive, and clockwise is negative;
Rotate left, the y axis is negative, rotate right, y is positive;
Rotate up and x is negative, rotate down and x is positive.
2. Practical use
Modify the activity_main.xml code as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textViewx"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textViewy"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textViewz"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Modify the MainActivity code as follows:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sm;
TextView textViewx;
TextView textViewy;
TextView textViewz;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewx = (TextView) findViewById(R.id.textViewx);
textViewy = (TextView) findViewById(R.id.textViewy);
textViewz = (TextView) findViewById(R.id.textViewz);
// 获取传感器管理器
sm = (SensorManager)getSystemService(SENSOR_SERVICE);
// 调用方法获得需要的传感器
Sensor mSensorOrientation = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
// 注册监听器
// SENSOR_DELAY_FASTEST最灵敏
// SENSOR_DELAY_GAME 游戏的时候,不过一般用这个就够了
// SENSOR_DELAY_NORMAL 比较慢。
// SENSOR_DELAY_UI 最慢的
sm.registerListener(this, mSensorOrientation, android.hardware.SensorManager.SENSOR_DELAY_UI);
}
// 该方法在传感器的值发生改变的时候调用
@Override
public void onSensorChanged(SensorEvent event) {
float X = (float)Math.toDegrees(event.values[0]);
float Y = (float)Math.toDegrees(event.values[1]);
float Z = (float)Math.toDegrees(event.values[2]);
textViewx.setText("绕x轴转过的角速度\n"+ X );
textViewy.setText("绕y轴转过的角速度\n"+ Y );
textViewz.setText("绕z轴转过的角速度\n"+ Z );
}
// 当传感器的进度发生改变时会回调
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// 在activity变为不可见的时候,传感器依然在工作,这样很耗电,所以我们根据需求可以在onPause方法里面停掉传感器的工作
@Override
public void onPause() {
sm.unregisterListener(this);
super.onPause();
}
}