PageRenderTime 24ms CodeModel.GetById 19ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/there/src/com/google/marvin/there/Compass.java

http://eyes-free.googlecode.com/
Java | 73 lines | 51 code | 15 blank | 7 comment | 7 complexity | 69630bbae212f3942edf0ebfa0e4a103 MD5 | raw file
 1package com.google.marvin.there;
 2
 3import android.content.Context;
 4import android.hardware.SensorListener;
 5import android.hardware.SensorManager;
 6
 7/**
 8 * Compass uses the magnetic compass to track the current heading.
 9 * @author clchen@google.com (Charles L. Chen)
10 */
11
12public class Compass {
13  private Context ctx;
14
15  public Compass(Context context) {
16    ctx = context;
17    sensorOk = true;
18    sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
19    sensorManager.registerListener(mListener, SensorManager.SENSOR_ORIENTATION,
20        SensorManager.SENSOR_DELAY_GAME);
21  }
22
23  private static final String[] DIRECTION_NAMES =
24      {"north", "north north east", "north east", "east north east", "east", "east south east",
25          "south east", "south south east", "south", "south south west", "south west",
26          "west south west", "west", "west north west", "north west", "north north west", "north"};
27
28  private SensorManager sensorManager;
29
30  private float currentHeading = -1;
31  private boolean sensorOk;
32
33  /**
34   * Handles the sensor events for changes to readings and accuracy
35   */
36  private final SensorListener mListener = new SensorListener() {
37    public void onSensorChanged(int sensor, float[] values) {
38      currentHeading = values[0]; // Values are yaw (heading), pitch, and roll.
39    }
40
41    public void onAccuracyChanged(int arg0, int arg1) {
42      sensorOk = (arg1 == SensorManager.SENSOR_STATUS_ACCURACY_HIGH);
43    }
44  };
45
46  public String getCurrentHeading() {
47    if (currentHeading == -1) {
48      return "";
49    }
50    if (!sensorOk) {
51      return "";
52    }
53    int index = (int) ((currentHeading * 100 + 1125) / 2250);
54    return DIRECTION_NAMES[index];
55  }
56  
57  public double getCurrentHeadingValue() {
58    if (currentHeading == -1) {
59      return -1;
60    }
61    if (!sensorOk) {
62      return -1;
63    }
64    return currentHeading;
65  }
66
67  public void shutdown() {
68    sensorManager.unregisterListener(mListener);
69  }
70
71
72
73}