basic knowledge
The acceleration sensor can return the acceleration values of the x, y, and z axes, which are affected by gravity.
Put the phone flat on the table, the x, y, and z axes default to 9.81; the phone's downward z-axis is -9.81.
Tilt the phone to the left, the x-axis is positive, tilt it to the right, and x is negative;
Tilt the phone up, the y axis is negative, and down, the x is positive.
The following figure shows the values of the xyz axis from top to bottom in turn. It can be seen that the state of the mobile phone is tilted to the right.
practical use
Create a new project, modify the layout file activity_main.xml, the code is 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_ACCELEROMETER);
// 注册监听器
//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 = event.values[0];
float Y = event.values[1];
float Z = event.values[2];
textViewx.setText(X+"");
textViewy.setText(Y+"");
textViewz.setText(Z+"");
}
// 当传感器的进度发生改变时回调,sensor是传感器对象,accuracy是传感器新的精度
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// 在activity变为不可见的时候,传感器依然在工作,这样很耗电,所以我们根据需求可以在onPause方法里面停掉传感器的工作
@Override
public void onPause() {
// 取消监听器的注册
sm. unregisterListener(this);
super.onPause();
}
}
When running on a mobile phone, you will find that the decimal part of the three values keeps changing, which is normal.