需求
需要做一个类似作业帮拍照,判断用户是否把手机放平的功能。
使用手机重力感应来实现
Activity实现SensorEventListener方法
//注册感应器
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, sensor, sensorManager.SENSOR_DELAY_NORMAL);
重写监听方法
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor == null) {
return;
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
int x = (int) event.values[0];
int y = (int) event.values[1];
int z = (int) event.values[2];
Log.e("dbj","x = "+ x +",y = " + y + " z = "+ z);
if (Math.abs(x) > 1 || Math.abs(y) > 1 || Math.abs(z) != 9){
Toast.makeText(this,"请把手机水平拍摄",Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}