1 加速度传感器 TYPE_ACCELEROMETER
2 温度传感器 TYPE_AMBIENT_TEMPERATURE
3 陀螺仪传感器 TYPE_GYROSCOPE
4 光线传感器 TYPE_LIGHT
5 磁场传感器 TYPE_MAGNETIC_FIELD
6 压力传感器 TYPE_PRESSURE
7 临近传感器 TYPE_PROXIMITY
8 湿度传感器 TYPE_RELATIVE_HUMIDITY
9 方向传感器 TYPE_ORIENTATION
10 重力传感器 TYPE_GRAVITY
11 线性加速传感器 TYPE_LINEAR_ACCELERATION
12 旋转向量传感器 TYPE_ROTATION_VECTOR
注意:1-8是硬件传感器,9是软件传感器,其中方向传感器的数据来自重力和磁场传感器,10-12是硬件或软件传感器。
传感器的调用套路代码
import android.R.integer;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
public class MySensorListener implements SensorEventListener {
private SensorManager mSensorManager;
private Context mContext;
private Sensor mSensor;
public MySensorListener(Context context)
{
this.mContext = context;
}
public void start()
{
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager != null)
{
// 获得方向传感器 要获取什么传感器就传什么
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
/*从上往下灵敏度依次降低:
1. SENSOR_DELAY_FASTEST
2. SENSOR_DELAY_GAME
3. SENSOR_DELAY_UI
4. SENSOR_DELAY_NORMAL
*/
if (mSensor != null)
{
mSensorManager.registerListener(this, mSensor,
SensorManager.SENSOR_DELAY_GAME);
}
}
public void stop()
{
mSensorManager.unregisterListener(this);
}
//每一种传感器的event的值可能不同
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
//获取手机在不同方向上加速度的变化
float valuesX = Math.abs(event.values[0]);
float valuesY = Math.abs(event.values[1]);
float valuesZ = Math.abs(event.values[2]);
if (mOnOrientationListener != null)
{
mOnOrientationListener.onOrientationChanged(valuesX,valuesY,valuesZ);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private OnOrientationListener mOnOrientationListener;
public void setOnOrientationListener(
OnOrientationListener mOnOrientationListener)
{
this.mOnOrientationListener = mOnOrientationListener;
}
public interface OnOrientationListener
{
void onOrientationChanged(float x,float y,float z);
}
}
activity中调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorListener=new MySensorListener(getApplicationContext());
mSensorListener.setOnOrientationListener(new OnOrientationListener() {
@Override
public void onOrientationChanged() {
//playSoundAndVibrator();
}
});
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
if(mSensorListener!=null){
mSensorListener.start();
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if(mSensorListener!=null){
mSensorListener.stop();
}
}