public class MainActivity extends AppCompatActivity {
private SensorManager sensorManager;
private SensorEventListener listener;
private Sensor sensor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
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>15||yValue>15||zValue>15){
Toast.makeText(MainActivity.this, "摇一摇", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
sensorManager.registerListener(listener, sensor,SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(sensorManager!=null){
// 注销监听器
sensorManager.unregisterListener(listener);
}
}
}
加速度传感器
最新推荐文章于 2022-05-10 00:25:50 发布