Android using Accelerometer

时间:2023-04-02 15:46:26

http://code.tutsplus.com/tutorials/using-the-accelerometer-on-android--mobile-22125

public class Main extends Activity implements SensorEventListener {
private SensorManager senSensorManager;
private Sensor senAccelerometer; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
} @Override
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor mySensor = sensorEvent.sensor; if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2]; long curTime = System.currentTimeMillis(); if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime; float speed = Math.abs(x + y + z - last_x - last_y - last_z)/ diffTime * 10000; if (speed > SHAKE_THRESHOLD) { } last_x = x;
last_y = y;
last_z = z;
}
}
}
}