【Android入门到项目实战-- 9.5】—— 陀螺仪传感器的详细使用教程

目录

陀螺仪传感器

1、基础知识

 2、实战使用


陀螺仪传感器

1、基础知识

        返回x、y、z轴的角加速度数据。

        水平逆时针旋转,z轴为正,顺时针为负;

        向左旋转,y轴为负,向右旋转,y为正;

        向上旋转,x为负,向下旋转,x为正。

 2、实战使用

修改activity_main.xml代码如下:

扫描二维码关注公众号,回复: 15143302 查看本文章
<?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>

修改MainActivity代码如下:

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();
    }
}

猜你喜欢

转载自blog.csdn.net/Tir_zhang/article/details/130545047
9.5