PageRenderTime 14ms CodeModel.GetById 1ms app.highlight 9ms RepoModel.GetById 2ms app.codeStats 0ms

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

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