PageRenderTime 26ms CodeModel.GetById 16ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/remindme/src/com/google/marvin/remindme/ShakeDetector.java

http://eyes-free.googlecode.com/
Java | 70 lines | 55 code | 15 blank | 0 comment | 6 complexity | 1583dfcdaacf9dc9205a002b32b2787c MD5 | raw file
 1package com.google.marvin.remindme;
 2
 3import android.content.Context;
 4import android.hardware.SensorListener;
 5import android.hardware.SensorManager;
 6
 7public class ShakeDetector {
 8
 9  public interface ShakeListener {
10    public void onShakeDetected();
11  }
12
13
14  private SensorListener mListener;
15  private ShakeListener cb;
16  private SensorManager sensorManager;
17
18  public ShakeDetector(Context context, ShakeListener callback) {
19    cb = callback;
20    mListener = new SensorListener() {
21      private final double deletionForce = .8;
22      private final int deletionCount = 2;
23      int shakeCount = 0;
24      boolean lastShakePositive = false;
25      private int shakeCountTimeout = 500;
26
27      public void onSensorChanged(int sensor, float[] values) {
28        if ((values[1] > deletionForce) && !lastShakePositive) {
29          (new Thread(new resetShakeCount())).start();
30          shakeCount++;
31          lastShakePositive = true;
32        } else if ((values[1] < -deletionForce) && lastShakePositive) {
33          (new Thread(new resetShakeCount())).start();
34          shakeCount++;
35          lastShakePositive = false;
36        }
37        if (shakeCount > deletionCount) {
38          shakeCount = 0;
39          cb.onShakeDetected();
40        }
41      }
42
43      public void onAccuracyChanged(int arg0, int arg1) {
44      }
45
46      class resetShakeCount implements Runnable {
47        public void run() {
48          try {
49            Thread.sleep(shakeCountTimeout);
50            shakeCount = 0;
51          } catch (InterruptedException e) {
52            e.printStackTrace();
53          }
54        }
55      }
56    };
57    
58    
59    sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
60    sensorManager.registerListener(mListener, SensorManager.SENSOR_ACCELEROMETER,
61        SensorManager.SENSOR_DELAY_FASTEST);
62  }
63  
64  public void shutdown() {
65    sensorManager.unregisterListener(mListener);
66  }
67
68
69
70}