方向传感器

package com.pingyijinren.test;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class IndexActivity extends AppCompatActivity {
    private SensorManager sensorManager;
    private Sensor magneticSensor;
    private Sensor accelerometerSensor;
    private SensorEventListener sensorEventListener;
    private float[] accelerometerValues=new float[3];
    private float[] magneticValues=new float[3];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

        sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
        accelerometerSensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        magneticSensor=sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        sensorEventListener=new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
                    accelerometerValues=event.values.clone();
                }
                else if(event.sensor.getType()==Sensor.TYPE_MAGNETIC_FIELD){
                    magneticValues=event.values.clone();
                }
                float[] R=new float[9];
                float[] values=new float[3];
                SensorManager.getRotationMatrix(R,null,accelerometerValues,magneticValues);
                SensorManager.getOrientation(R,values);
                Log.d("MainActivity",Math.toDegrees(values[0])+"");
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        };
        sensorManager.registerListener(sensorEventListener,accelerometerSensor,SensorManager.SENSOR_DELAY_GAME);
        sensorManager.registerListener(sensorEventListener,magneticSensor,SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        if(sensorManager!=null){
            sensorManager.unregisterListener(sensorEventListener);
        }
    }
}

 

posted @ 2016-05-20 11:17  zqxLonely  阅读(214)  评论(0编辑  收藏  举报