原理:手机系统有传感器,调用手机传感器,并让手机振动
public abstract class ShakeListener implements SensorEventListener{ private int duration = 100;//采样时间间隔 private long lastTime; private float lastPointX;//上一个点的x轴的加速度信息 private float lastPointY; private float lastPointZ; private float shake;//单次增量 private float totalShake;//总增量 private float swithValue = 100;//判断是否摇晃手机的最大值 public ShakeListener(){ init(); } private void init(){ lastTime = 0; lastPointX = 0; lastPointY = 0; lastPointZ = 0; shake = 0; totalShake = 0; } @Override public void onSensorChanged(SensorEvent event) { if(lastTime == 0){ lastTime = System.currentTimeMillis(); lastPointX = event.values[SensorManager.DATA_X]; lastPointY = event.values[SensorManager.DATA_Y]; lastPointZ = event.values[SensorManager.DATA_Z]; }else{ long currentTime = System.currentTimeMillis(); if(currentTime - lastTime > duration){ //第二个点 float x = event.values[SensorManager.DATA_X]; float y = event.values[SensorManager.DATA_Y]; float z = event.values[SensorManager.DATA_Z]; //每次传入的数据都存在微小的变动 float dx = Math.abs(x - lastPointX); float dy = Math.abs(y - lastPointY); float dz = Math.abs(z - lastPointZ); if(dx < 1){ dx = 0; } if(dy < 1){ dy = 0; } if(dz <1){ dz = 0; } shake = dx + dy + dz; if(shake == 0){ //处于静止状态 init(); } totalShake += shake; if(totalShake > swithValue){ //说明是在摇晃手机 //机选一注彩票,并且有震动 shakeCrateLottery(); init(); }else{ lastTime = System.currentTimeMillis(); lastPointX = event.values[SensorManager.DATA_X]; lastPointY = event.values[SensorManager.DATA_Y]; lastPointZ = event.values[SensorManager.DATA_Z]; } } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public abstract void shakeCrateLottery(); }