android手机晃动事件实例

 

注册监听

sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
  int sensorType = android.hardware.Sensor.TYPE_ACCELEROMETER;
  sm.registerListener(mySensorEventListener, sm
    .getDefaultSensor(sensorType),
    SensorManager.SENSOR_DELAY_FASTEST);

 

事件触发
 public final SensorEventListener mySensorEventListener = new SensorEventListener() {

  @Override
  public void onAccuracyChanged(android.hardware.Sensor sensor,
    int accuracy) {
   // TODO Auto-generated method stub

  }

  @Override
  public void onSensorChanged(SensorEvent event) {
   // TODO Auto-generated method stub
   if (event.sensor.getType() == android.hardware.Sensor.TYPE_ACCELEROMETER) {

    // 获取加速度传感器的三个参数

    float x = event.values[SensorManager.DATA_X];

    float y = event.values[SensorManager.DATA_Y];

    float z = event.values[SensorManager.DATA_Z];

    // 获取当前时刻的毫秒数

    curTime = System.currentTimeMillis();

    // 100毫秒检测一次

    float aa = curTime - lastTime;

    if ((curTime - lastTime) > 100) {

     duration = (curTime - lastTime);

     // 看是不是刚开始晃动

     if (last_x == 0.0f && last_y == 0.0f && last_z == 0.0f) {

      // last_x、last_y、last_z同时为0时,表示刚刚开始记录

      initTime = System.currentTimeMillis();

     } else {

      // 单次晃动幅度

      shake = (Math.abs(x - last_x) + Math.abs(y - last_y) + Math
        .abs(z - last_z));
      // / duration * 1000;

     }

     // 把每次的晃动幅度相加,得到总体晃动幅度

     totalShake += shake;

     // 判断是否为摇动

     if (shake > 20) {
      action();
      onVibrator();

      initShake();
     }
     last_x = x;

     last_y = y;

     last_z = z;

     lastTime = curTime;

    }

   }
  }
 };

 

 

其中 onVibrator();是触发震动 :


 private void onVibrator() {
  Vibrator vibrator = (Vibrator) context
    .getSystemService(Context.VIBRATOR_SERVICE);
  if (vibrator == null) {
   Vibrator localVibrator = (Vibrator) context.getApplicationContext()
     .getSystemService("vibrator");
   vibrator = localVibrator;
  }
  vibrator.vibrate(100L);
 }

掉用系统震动这样反应快 ,自己写的long数组

调用有时间间隔,效果不好

 

initShake();初始化事件触发的几个变量:


 public void initShake() {

  lastTime = 0;

  duration = 0;

  curTime = 0;

  initTime = 0;

  last_x = 0.0f;

  last_y = 0.0f;

  last_z = 0.0f;

  shake = 0.0f;

  totalShake = 0.0f;

你可能感兴趣的:(android,service,action,手机,float,delay)