Sensor(ACCELEROMETER)

package com.example.sensor01;



import java.util.List;



import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.widget.TextView;



public class MainActivity extends Activity implements SensorEventListener{

    

    private SensorManager mSensorManager;

    private TextView textview;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        

        textview = (TextView) findViewById(R.id.content);

                

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        

        //TYPE_ACCELEROMETER 重力感应加速度(三轴)

        List sensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);

        

        if(sensors.size() > 0){

            Sensor sensor = (Sensor) sensors.get(0);

            /*SENSOR_DELAY_FASTEST: 以最快的速度获得传感器数据

            SENSOR_DELAY_GAME: 适合与在游戏中获得传感器数据

            SENSOR_DELAY_UI :适合于在ui空间中获得数据

            SENSOR_DELAY_NORMAL: 以一般的速度获得传感器数据*/

            mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);

        }

    }



    @Override

    public void onAccuracyChanged(Sensor arg0, int arg1) {

        // TODO Auto-generated method stub    

    }



    @Override

    public void onSensorChanged(SensorEvent event) {

        float gx = 0,gy = 0,gz = 0;

        

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){

            gx = event.values[0];//x轴,单位m/x^2

            gy = event.values[1];//y轴,单位m/x^2

            gz = event.values[2];//z轴,单位m/x^2

        }

        

        //加速度数值是设备以地球为参照物的加速度减去重力加速度的叠加后的值

        //gx = g * cos(ax); 手机横屏垂直,该值为9.8

        //gy = g * cos(ay); 手机竖屏垂直,该值为9.8

        //gz = g * cos(az); 手机屏幕水平朝上,该值为9.8

        

        textview.setText(String.valueOf(gx) + "   " + String.valueOf(gy) + "  " + String.valueOf(gz));                

    }

}

 

你可能感兴趣的:(sensor)