1、activity 实现加速度监听类 。。。。implements SensorEventListener
public class MainActivity extends AppCompatActivity implements SensorEventListener {
2、activity实现两个方法:
@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) { bb++; if (bb%3==0) Log.i("lgq","yyyyyy=--------"+bb); // getRandomNumber(); } last_x = x; last_y = y; last_z = z; } } } @Override public void onAccuracyChanged(Sensor sensor, int i) { }
3、初始化数据,设置加速度监听,实现摇一摇功能
初始化:
private long lastUpdate = 0; private float last_x, last_y, last_z; private static final int SHAKE_THRESHOLD = 600; private SensorManager senSensorManager; private Sensor senAccelerometer;
设置加速度监听:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL); }
4、运行项目摇一摇即可实现执行回调方法onSensorChanged,实现方法打印:
Log.i("lgq","yyyyyy=--------"+bb);