最近项目需要摇一摇:在网上参考很多案列,写出了基本逻辑:
1,通过资源拿到SensorManager和Sensor,并且注册监听器;
2,编写监听器,触发摇一摇Sensor
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
private SensorEventListener listener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { // 加速度可能会是负值,所以要取它们的绝对值 float xValue = Math.abs(event.values[0]); float yValue = Math.abs(event.values[1]); float zValue = Math.abs(event.values[2]); if (xValue > 12 || yValue > 12 || zValue > 12) { // 认为用户摇动了手机,触发摇一摇逻辑 } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } };