分类
Android开发

Android Sensor重力感应

1、定义变量

private SensorManager mSensorManager = null;
private Sensor mSensor = null;
private SensorEventListener mSensorEventListener = null;
private long lastUpdate = 0;
private float last_x,last_y,last_z;
private final float SHAKE_THRESHOLD = 800f;

2、初始化变量

private void initSensor(){
	mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	if(mSensorManager != null){
		mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		mSensorEventListener = new SensorEventListener() {
			@Override
			public void onSensorChanged(SensorEvent event) {
				// TODO Auto-generated method stub
				long curTime = System.currentTimeMillis();
				// 每100毫秒检测一次
				if ((curTime – lastUpdate) > 100) {
					long diffTime = (curTime – lastUpdate);
					lastUpdate = curTime;

					float x = event.values[SensorManager.DATA_X];
					float y = event.values[SensorManager.DATA_Y];
					float z = event.values[SensorManager.DATA_Z];

					float speed = Math.abs(x + y + z – last_x – last_y
					- last_z)
					/ diffTime * 10000;
					Log.i("speed", "speed=" + speed);
					if (speed > SHAKE_THRESHOLD) {
						//do something相应的处理
					}
					last_x = x;
					last_y = y;
					last_z = z;
				}
			}

			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// TODO Auto-generated method stub
			}
		};
	}
}

3、注册、取消注册监听

@Override
protected void onResume() {
	if(mSensorManager != null){
		mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
	}
	super.onResume();
}

@Override
protected void onPause() {
	if(mSensorManager != null){
		mSensorManager.unregisterListener(mSensorEventListener);
	}
	super.onPause();
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

发表评论

电子邮件地址不会被公开。 必填项已用*标注