//模仿微信摇一摇 当加速度大于9.8时产生触发
public class MainActivity extends Activity {
private SensorManager sensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取SensorManager实例
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//指定具体的传感器类型
Sensor sensor = sensorManager .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//设定接口,指定传感器输出信息的更新速率
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (sensorManager != null) {
sensorManager.unregisterListener(listener);
}
}
private SensorEventListener listener = new SensorEventListener() {
//当传感器监测到得数值发生变化时就会调用该方法
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
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) {
// TODO Auto-generated method stub
}
};
}