1. 通过SensorManager 创建Sensor 对象
sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
2. 创建SensorEventListener 对象并实现它的两个方法
private SensorEventListener listener = new SensorEventListener(){
@Override
public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(android.hardware.SensorEvent event) {
}
};
3. 注册传感器
sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
记得要在onDestroy 中注销
@Override
protected void onDestroy() {
super.onDestroy();
if(sensorManager != null){
sensorManager.unregisterListener(listener);
}
}
完整程序:仿微信摇一摇
public class MainActivity extends Activity {
private SensorManager sensorManager;
private SensorEventListener listener = new SensorEventListener(){
@Override
public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(android.hardware.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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
}
}
}