public static List<Location> getPoints(File gpxFile) throws Exception {
    List<Location> points;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    FileInputStream fis = new FileInputStream(gpxFile);
    Document dom = builder.parse(fis);
    Element root = dom.getDocumentElement();
    NodeList items = root.getElementsByTagName("trkpt");

    points = new ArrayList<Location>();

    for (int j = 0; j < items.getLength(); j++) {
      Node item = items.item(j);
      NamedNodeMap attrs = item.getAttributes();
      NodeList props = item.getChildNodes();

      Location pt = new Location("test");

      pt.setLatitude(Double.parseDouble(attrs.getNamedItem("lat").getNodeValue()));
      pt.setLongitude(Double.parseDouble(attrs.getNamedItem("lon").getNodeValue()));

      for (int k = 0; k < props.getLength(); k++) {
        Node item2 = props.item(k);
        String name = item2.getNodeName();

        if (name.equalsIgnoreCase("ele")) {
          pt.setAltitude(Double.parseDouble(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("course")) {
          pt.setBearing(Float.parseFloat(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("speed")) {
          pt.setSpeed(Float.parseFloat(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("hdop")) {
          pt.setAccuracy(Float.parseFloat(item2.getFirstChild().getNodeValue()) * 5);
        }
        if (name.equalsIgnoreCase("time")) {
          pt.setTime((getDateFormatter().parse(item2.getFirstChild().getNodeValue())).getTime());
        }
      }

      for (int y = 0; y < props.getLength(); y++) {
        Node item3 = props.item(y);
        String name = item3.getNodeName();
        if (!name.equalsIgnoreCase("ele")) {
          continue;
        }
        pt.setAltitude(Double.parseDouble(item3.getFirstChild().getNodeValue()));
      }

      points.add(pt);
    }

    fis.close();

    return points;
  }
Exemple #2
0
 public Location getLocation() {
   Location location = new Location("Station");
   location.setAltitude(stationaltitude);
   location.setLatitude(stationlatitude);
   location.setLongitude(stationlongitude);
   return location;
 }
Exemple #3
0
  public static ArrayList<ARGeoNode> cleanNoLocation(
      Activity activity,
      ARLayerManager layers,
      ArrayList<GeoNode> list,
      float[] location,
      float distanceFilter) {
    ArrayList<ARGeoNode> cleaned_list = new ArrayList<ARGeoNode>();

    Location mLocation = new Location("");
    mLocation.setLatitude(location[0]);
    mLocation.setLongitude(location[1]);

    Location resLocation = new Location("");
    for (int i = list.size() - 1; i >= 0; i--) {
      GeoNode resource = list.get(i);
      if (resource == null) {
        Log.e("ARUtils", "Vacio");
        continue;
      }
      if ((resource.getLatitude() != -1.0) && (resource.getLongitude() != -1.0)) {
        if (distanceFilter > 0) {
          resLocation.setLatitude(resource.getLatitude());
          resLocation.setLongitude(resource.getLongitude());
          resLocation.setAltitude(mLocation.getAltitude());

          if (mLocation.distanceTo(resLocation) > distanceFilter) continue;
        }
        ARGeoNode node = new ARGeoNode((ARBase) activity, resource, layers.getInfoLayer());
        cleaned_list.add(node);
      }
    }

    return cleaned_list;
  }
  public GameLoopView(Context context) {
    super(context);

    // remember the context for finding resources
    this.context = context;

    score = 0;

    // want to know when the surface changes
    surfaceHolder = getHolder();
    surfaceHolder.addCallback(this);

    // set a fixed location

    location = new Location("FIXED POSITION");
    location.setLatitude(0);
    location.setAltitude(0);
    location.setLongitude(0);

    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point p = new Point();
    display.getSize(p);
    screenWidth = p.x;
    screenHeight = p.y;

    // game loop thread
    thread = new GameLoopThread();
  }
  /**
   * Fills a track point from a cursor.
   *
   * @param cursor the cursor pointing to a location.
   * @param indexes the cached track points indexes
   * @param location the track point
   */
  private void fillTrackPoint(Cursor cursor, CachedTrackPointsIndexes indexes, Location location) {
    location.reset();

    if (!cursor.isNull(indexes.longitudeIndex)) {
      location.setLongitude(((double) cursor.getInt(indexes.longitudeIndex)) / 1E6);
    }
    if (!cursor.isNull(indexes.latitudeIndex)) {
      location.setLatitude(((double) cursor.getInt(indexes.latitudeIndex)) / 1E6);
    }
    if (!cursor.isNull(indexes.timeIndex)) {
      location.setTime(cursor.getLong(indexes.timeIndex));
    }
    if (!cursor.isNull(indexes.altitudeIndex)) {
      location.setAltitude(cursor.getFloat(indexes.altitudeIndex));
    }
    if (!cursor.isNull(indexes.accuracyIndex)) {
      location.setAccuracy(cursor.getFloat(indexes.accuracyIndex));
    }
    if (!cursor.isNull(indexes.speedIndex)) {
      location.setSpeed(cursor.getFloat(indexes.speedIndex));
    }
    if (!cursor.isNull(indexes.bearingIndex)) {
      location.setBearing(cursor.getFloat(indexes.bearingIndex));
    }
    if (location instanceof MyTracksLocation && !cursor.isNull(indexes.sensorIndex)) {
      MyTracksLocation myTracksLocation = (MyTracksLocation) location;
      try {
        myTracksLocation.setSensorDataSet(
            SensorDataSet.parseFrom(cursor.getBlob(indexes.sensorIndex)));
      } catch (InvalidProtocolBufferException e) {
        Log.w(TAG, "Failed to parse sensor data.", e);
      }
    }
  }
Exemple #6
0
  public boolean CheckForUpdate() {

    Result result = GetJSONData();
    if (result != null) {
      if (result.latitude != null) {
        if (currentlocation != null) {
          if (result.latitude != jsonlocation.getLatitude()) {
            // New data!
            if (jsonlocation.getLatitude() != 0.0) {
              pastlocation.setLatitude(jsonlocation.getLatitude());
              pastlocation.setLongitude(jsonlocation.getLongitude());
              pastlocation.setAltitude(jsonlocation.getAltitude());
            }

            jsonlocation.setLatitude(result.latitude);
            jsonlocation.setLongitude(result.longitude);
            jsonlocation.setAltitude(result.altitude);

            currentlocation.setLatitude(jsonlocation.getLatitude());
            currentlocation.setLongitude(jsonlocation.getLongitude());
            currentlocation.setAltitude(jsonlocation.getAltitude());

            if (!FirstLock && !SecondLock) {
              FirstLock = true;
              dataSent = false;
            } else if (FirstLock && !SecondLock) {
              SecondLock = true;
              dataSent = false;
            }

            TimeSinceLastUpdate = 0;
            return true;
          } else {
            TimeSinceLastUpdate += 5;
            return false;
          }
        }
      } else {
        TimeSinceLastUpdate += 5;
        return false;
      }
      TimeSinceLastUpdate += 5;
      return false;
    }
    return false;
  }
Exemple #7
0
 public float getDistance(Tab target, Location toLoc) {
   Location loc = new Location("t2f");
   loc.setAltitude(target.alt);
   loc.setLatitude(target.lat);
   loc.setLongitude(target.lon);
   float distance = loc.distanceTo(toLoc) / 1000;
   return distance;
 }
  /**
   * Test if {@link LocationMessage#altitude} and {@link LocationMessage#accuracy} is correctly
   * converted. (These are the only fields that not implicit tested by the other methods.)
   */
  public void testToAndroidLocation() {
    Location remoteLocation = new Location((String) null);
    remoteLocation.setAltitude(33);
    remoteLocation.setAccuracy(42);

    LocationMessage locationMessage = new LocationMessage(remoteLocation, true, false, false);
    Location actual = locationMessage.toAndroidLocation();
    assertEquals(33d, actual.getAltitude());
    assertEquals(42f, actual.getAccuracy());
  }
Exemple #9
0
 public static android.location.Location protoLocationToAndroidLocation(
     de.uvwxy.daisy.proto.Messages.Location protoLoc) {
   android.location.Location androidLoc = new android.location.Location(protoLoc.getProvider());
   androidLoc.setAccuracy((float) protoLoc.getAccuracy());
   androidLoc.setAltitude(protoLoc.getAltitude());
   androidLoc.setBearing((float) protoLoc.getBearing());
   androidLoc.setLatitude(protoLoc.getLatitude());
   androidLoc.setLongitude(protoLoc.getLongitude());
   androidLoc.setSpeed((float) protoLoc.getSpeed());
   androidLoc.setTime(protoLoc.getTime());
   return androidLoc;
 }
 public Location getLocation() {
   if (isBeforeFirst() || isAfterLast()) return null;
   // First get the provider out so you can use the constructor
   String provider = getString(getColumnIndex(COLUMN_LOCATION_PROVIDER));
   Location loc = new Location(provider);
   // Populate the remaining properties
   loc.setLongitude(getDouble(getColumnIndex(COLUMN_LOCATION_LONGITUDE)));
   loc.setLatitude(getDouble(getColumnIndex(COLUMN_LOCATION_LATITUDE)));
   loc.setAltitude(getDouble(getColumnIndex(COLUMN_LOCATION_ALTITUDE)));
   loc.setTime(getLong(getColumnIndex(COLUMN_LOCATION_TIMESTAMP)));
   return loc;
 }
 private Location map(LatLng latLng1, float bearing) {
   Location location = new Location(PROVIDER);
   location.setLatitude(latLng1.lat);
   location.setLongitude(latLng1.lng);
   location.setAccuracy(3.0f);
   location.setTime(System.currentTimeMillis());
   location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
   location.setBearing(bearing);
   location.setSpeed(13.4f);
   location.setAltitude(0d);
   return location;
 }
 private LinkedList<LinkedList<Pair<Location, Long>>> prepareTraceWithTime(int number) {
   LinkedList<LinkedList<Pair<Location, Long>>> trace =
       new LinkedList<LinkedList<Pair<Location, Long>>>();
   for (int i = 0; i < number; i++) {
     LinkedList<Pair<Location, Long>> subrun = new LinkedList<Pair<Location, Long>>();
     for (int j = 0; j < number; j++) {
       Location l = new Location("");
       l.setLatitude(number * i * j);
       l.setLongitude(number * i / (j + 1));
       l.setAltitude(number);
       subrun.add(new Pair<Location, Long>(l, number * 13000L));
     }
     trace.add(subrun);
   }
   return trace;
 }
  @SmallTest
  public void testWaypointXml_WithAltitude() {
    Gpx10AnnotateHandler annotateHandler = new Gpx10AnnotateHandler(null, null, null, null);

    Location loc = new Location("MOCK");
    loc.setLatitude(12.193);
    loc.setLongitude(19.111);
    loc.setAltitude(9001);

    String actual =
        annotateHandler.GetWaypointXml(loc, "2011-09-17T18:45:33Z", "This is the annotation");
    String expected =
        "\n<wpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time><name>This is the annotation</name><src>MOCK</src></wpt>\n";

    assertEquals("Basic waypoint XML", expected, actual);
  }
  @SmallTest
  public void testPlacemarkXml_BasicInfo() {

    Kml22AnnotateHandler kmlHandler = new Kml22AnnotateHandler(null, null, null);
    Location loc = new Location("MOCK");
    loc.setLatitude(12.193);
    loc.setLongitude(19.111);
    loc.setAltitude(9001);
    loc.setBearing(91.88f);
    loc.setSpeed(188.44f);

    String actual = kmlHandler.GetPlacemarkXml("This is the annotation", loc);
    String expected =
        "<Placemark><name>This is the annotation</name><Point><coordinates>19.111,12.193,9001.0</coordinates></Point></Placemark>\n";

    assertEquals("Basic Placemark XML", expected, actual);
  }
Exemple #15
0
  private List<Location> makeGpsDataFromGqLog(Context context, String gqLogName)
      throws NoSuchElementException {
    List<Location> locations = new ArrayList<Location>();

    AssetManager assetManager = context.getResources().getAssets();
    InputStream input;
    try {
      input = assetManager.open(gqLogName);
    } catch (IOException e) {
      Log.e(TAG, "asset open failed.", e);
      return locations;
    }

    try {
      final long now = System.currentTimeMillis();
      Long prev = null;
      List<String> lines = readAsStringList(input, "UTF-8");
      for (String line : lines) {
        String[] cols = line.split(",");

        if (cols.length < 8) {
          continue;
        }

        long time = Long.valueOf(cols[0]) * 1000;
        Location location = new Location(PROVIDER_NAME);
        location.setLatitude(Double.valueOf(cols[1]));
        location.setLongitude(Double.valueOf(cols[2]));
        location.setAltitude(Double.valueOf(cols[3]));
        location.setAccuracy(Float.valueOf(cols[4]));

        if (prev == null) {
          location.setTime(now);
        } else {
          location.setTime(now + (time - prev));
        }
        prev = time;
        locations.add(location);
      }
    } catch (IOException e) {
      Log.w(TAG, "location parse failed.", e);
    }

    return locations;
  }
 private void readGeometry(JsonReader reader) throws IOException {
   String s;
   reader.beginObject();
   while (reader.hasNext()) {
     s = reader.nextName();
     if (s.equals("coordinates")) {
       reader.beginArray();
       location = new Location("http://earthquake.usgs.gov/");
       location.setLongitude(reader.nextDouble());
       location.setLatitude(reader.nextDouble());
       location.setAltitude(-reader.nextDouble());
       reader.endArray();
     } else {
       reader.skipValue();
     }
   }
   reader.endObject();
 }
Exemple #17
0
  private Location createLocation(float latitude, float longitude, double height) {
    Location location = new Location(PROVIDER_NAME);
    location.setLatitude(latitude);
    location.setLongitude(longitude);
    location.setAltitude(height);
    location.setAccuracy(1.0f);
    location.setTime(java.lang.System.currentTimeMillis());
    // location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    try {
      Method makeComplete = Location.class.getMethod("makeComplete");
      if (makeComplete != null) {
        makeComplete.invoke(location);
      }
    } catch (Exception e) {
    }

    return location;
  }
Exemple #18
0
  private List<Location> makeGpsDataFromGpx(Context context, String gpxPath)
      throws NoSuchElementException {
    List<Location> locations = new ArrayList<Location>();

    AssetManager assetManager = context.getResources().getAssets();
    InputStream input;
    try {
      input = assetManager.open(gpxPath);
    } catch (IOException e) {
      Log.e(TAG, "asset open failed.", e);
      return locations;
    }

    GpxParser parser = new GpxParser(new InputStreamReader(input));

    if (!parser.parse()) {
      throw new NoSuchElementException("GpxParser.parse failed.");
    }
    Track[] tracks = parser.getTracks();
    if (tracks == null || tracks.length <= 0) {
      return locations;
    }

    final long now = System.currentTimeMillis();
    Long prev = null;
    for (TrackPoint point : tracks[0].getPoints()) {
      Location location = new Location(PROVIDER_NAME);
      location.setLatitude(point.getLatitude());
      location.setLongitude(point.getLongitude());
      location.setAccuracy(10f);
      location.setAltitude(point.getElevation());
      if (prev == null) {
        location.setTime(now);
      } else {
        location.setTime(now + (point.getTime() - prev));
      }
      prev = point.getTime();
      // NOTE ignore			location.setTime(point.getTime());
      locations.add(location);
    }

    return locations;
  }
  @SmallTest
  public void testTrackPointXml_NewTrackSegment() {

    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, true, 0, null);

    Location loc = new Location("MOCK");
    loc.setLatitude(12.193);
    loc.setLongitude(19.111);
    loc.setAltitude(9001);
    loc.setBearing(91.88f);
    loc.setSpeed(188.44f);

    String actual = writeHandler.GetTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected =
        "<trkseg><trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>"
            + "<course>91.88</course><speed>188.44</speed><src>MOCK</src></trkpt>\n</trkseg></trk></gpx>";

    assertEquals("Trackpoint XML with a new segment", expected, actual);
  }
  private void ReadFile() {
    long ticks = 0;
    try {
      BufferedReader br = new BufferedReader(new FileReader(mFile));
      char[] buf = new char[(int) mFile.length()];
      br.read(buf, 0, (int) mFile.length());
      br.close();
      String text = String.copyValueOf(buf);

      String[] lines = text.split("\n");

      mCoords.clear();
      for (int i = 0; i < lines.length; i++) {
        String[] parts = lines[i].split(",");
        if (parts.length < 8) continue;

        if (parts[0].trim().equals("Date")) continue;

        Location location = new Location("File");
        int strength = 0;
        try {
          ticks = Long.parseLong(parts[1].trim());
          location.setTime(ticks);

          location.setLongitude(Double.parseDouble(parts[2].trim()));
          location.setLatitude(Double.parseDouble(parts[3].trim()));
          location.setAltitude(Double.parseDouble(parts[4].trim()));
          location.setAccuracy(Float.parseFloat(parts[5].trim()));
          location.setBearing(Float.parseFloat(parts[6].trim()));
          location.setSpeed(Float.parseFloat(parts[7].trim()));
          strength = Integer.parseInt(parts[8].trim());
        } catch (Exception e) {
          ErrorFile.WriteException(e, null);
        }

        mCoords.add(new GPSCoordinate(location, strength));
      }
    } catch (Exception e) {
      ErrorFile.WriteException(e, mContext);
    }
  }
  @SmallTest
  public void testTrackPointXml_BundledGeoIdHeight() {

    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, true, 0, null);

    Location loc = new Location("MOCK");
    loc.setLatitude(12.193);
    loc.setLongitude(19.111);
    loc.setAltitude(9001);
    loc.setBearing(91.88f);
    loc.setSpeed(188.44f);
    Bundle b = new Bundle();
    b.putString("GEOIDHEIGHT", "MYGEOIDHEIGHT");
    loc.setExtras(b);

    String actual = writeHandler.GetTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected =
        "<trkseg><trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>"
            + "<course>91.88</course><speed>188.44</speed><src>MOCK</src><geoidheight>MYGEOIDHEIGHT</geoidheight></trkpt>\n</trkseg></trk></gpx>";

    assertEquals("Trackpoint XML with a geoid height", expected, actual);
  }
    /**
     * Extract a Location from a list of properties from a Service description
     *
     * @param it iterator over the list of properties
     * @return the location on the map described by this set of properties
     */
    public static Location extractLocation(Iterator it) {
      Location loc = new Location("mygps");

      while (it.hasNext()) {
        Property p = (Property) it.next();

        String propertyName = p.getName();

        if (propertyName.equals(DFUpdaterBehaviour.PROPERTY_NAME_LOCATION_ALT)) {
          double altitude = Double.parseDouble((String) p.getValue());
          loc.setAltitude(altitude);
        } else if (propertyName.equals(DFUpdaterBehaviour.PROPERTY_NAME_LOCATION_LAT)) {
          double latitude = Double.parseDouble((String) p.getValue());
          loc.setLatitude(latitude);
        } else if (propertyName.equals(DFUpdaterBehaviour.PROPERTY_NAME_LOCATION_LONG)) {
          double longitude = Double.parseDouble((String) p.getValue());
          loc.setLongitude(longitude);
        }
      }

      return loc;
    }
  /** called from native code to update our position. */
  private void reportLocation(
      int flags,
      double latitude,
      double longitude,
      double altitude,
      float speed,
      float bearing,
      float accuracy,
      long timestamp) {
    if (VERBOSE)
      Log.v(
          TAG,
          "reportLocation lat: " + latitude + " long: " + longitude + " timestamp: " + timestamp);

    mLastFixTime = System.currentTimeMillis();
    // report time to first fix
    if (mTTFF == 0 && (flags & LOCATION_HAS_LAT_LONG) == LOCATION_HAS_LAT_LONG) {
      mTTFF = (int) (mLastFixTime - mFixRequestTime);
      if (DEBUG) Log.d(TAG, "TTFF: " + mTTFF);

      // notify status listeners
      synchronized (mListeners) {
        int size = mListeners.size();
        for (int i = 0; i < size; i++) {
          Listener listener = mListeners.get(i);
          try {
            listener.mListener.onFirstFix(mTTFF);
          } catch (RemoteException e) {
            Log.w(TAG, "RemoteException in stopNavigating");
            mListeners.remove(listener);
            // adjust for size of list changing
            size--;
          }
        }
      }
    }

    synchronized (mLocation) {
      mLocationFlags = flags;
      if ((flags & LOCATION_HAS_LAT_LONG) == LOCATION_HAS_LAT_LONG) {
        mLocation.setLatitude(latitude);
        mLocation.setLongitude(longitude);
        mLocation.setTime(timestamp);
      }
      if ((flags & LOCATION_HAS_ALTITUDE) == LOCATION_HAS_ALTITUDE) {
        mLocation.setAltitude(altitude);
      } else {
        mLocation.removeAltitude();
      }
      if ((flags & LOCATION_HAS_SPEED) == LOCATION_HAS_SPEED) {
        mLocation.setSpeed(speed);
      } else {
        mLocation.removeSpeed();
      }
      if ((flags & LOCATION_HAS_BEARING) == LOCATION_HAS_BEARING) {
        mLocation.setBearing(bearing);
      } else {
        mLocation.removeBearing();
      }
      if ((flags & LOCATION_HAS_ACCURACY) == LOCATION_HAS_ACCURACY) {
        mLocation.setAccuracy(accuracy);
      } else {
        mLocation.removeAccuracy();
      }

      try {
        mLocationManager.reportLocation(mLocation, false);
      } catch (RemoteException e) {
        Log.e(TAG, "RemoteException calling reportLocation");
      }
    }

    if (mStarted && mStatus != LocationProvider.AVAILABLE) {
      // we still want to time out if we do not receive MIN_FIX_COUNT
      // within the time out and we are requesting infrequent fixes
      if (mFixInterval < NO_FIX_TIMEOUT) {
        mAlarmManager.cancel(mTimeoutIntent);
      }

      // send an intent to notify that the GPS is receiving fixes.
      Intent intent = new Intent(GPS_FIX_CHANGE_ACTION);
      intent.putExtra(EXTRA_ENABLED, true);
      mContext.sendBroadcast(intent);
      updateStatus(LocationProvider.AVAILABLE, mSvCount);
    }

    if (mFixCount++ >= MIN_FIX_COUNT && mFixInterval > 1) {
      if (DEBUG) Log.d(TAG, "exceeded MIN_FIX_COUNT");
      hibernate();
    }
  }
Exemple #24
0
  /*
      public void onCreate(Bundle savedInstanceState){

          super.onCreate(savedInstanceState);
      }
  */
  @Override
  public void onStart() {
    super.onStart();

    textView = new TextView(this);

    /*

    SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        if(!manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME)){

            textView.setText("Error, could not register sensor listener");

        }*/

    try {
      sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);

      sensors = sensorMgr.getSensorList(Sensor.TYPE_ACCELEROMETER);
      if (sensors.size() > 0) sensorGrav = sensors.get(0);

      sensors = sensorMgr.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
      if (sensors.size() > 0) sensorMag = sensors.get(0);

      sensorMgr.registerListener(this, sensorGrav, SensorManager.SENSOR_DELAY_NORMAL);
      sensorMgr.registerListener(this, sensorMag, SensorManager.SENSOR_DELAY_NORMAL);

      locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
      locationMgr.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);

      try {
        /*defaulting to our place*/
        Location hardFix = new Location("ATL");
        hardFix.setLatitude(39.931261);
        hardFix.setLongitude(-75.051267);
        hardFix.setAltitude(1);

        try {
          Location gps = locationMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
          Location network = locationMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
          if (gps != null) currentLocation = (gps);
          else if (network != null) currentLocation = (network);
          else currentLocation = (hardFix);
        } catch (Exception ex2) {
          currentLocation = (hardFix);
        }
        onLocationChanged(currentLocation);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    } catch (Exception ex1) {
      try {
        if (sensorMgr != null) {
          sensorMgr.unregisterListener(this, sensorGrav);
          sensorMgr.unregisterListener(this, sensorMag);
          sensorMgr = null;
        }
        if (locationMgr != null) {
          locationMgr.removeUpdates(this);
          locationMgr = null;
        }
      } catch (Exception ex2) {
        ex2.printStackTrace();
      }
    }
    setContentView(textView);
  }
  /**
   * (non-Javadoc)
   *
   * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
   */
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // Log.d( TAG, "insert on "+uri );
    Uri insertedUri = null;
    int match = GPStrackingProvider.sURIMatcher.match(uri);
    List<String> pathSegments = null;
    long trackId;
    long segmentId;
    long waypointId = -1;
    switch (match) {
      case WAYPOINTS:
        pathSegments = uri.getPathSegments();
        trackId = Integer.parseInt(pathSegments.get(1));
        segmentId = Integer.parseInt(pathSegments.get(3));

        Location loc = new Location(TAG);

        Double latitude = values.getAsDouble(Waypoints.LATITUDE);
        Double longitude = values.getAsDouble(Waypoints.LONGITUDE);
        Long time = values.getAsLong(Waypoints.TIME);
        Float speed = values.getAsFloat(Waypoints.SPEED);
        if (time == null) {
          time = System.currentTimeMillis();
        }
        if (speed == null) {
          speed = 0f;
        }
        loc.setLatitude(latitude);
        loc.setLongitude(longitude);
        loc.setTime(time);
        loc.setSpeed(speed);

        if (values.containsKey(Waypoints.ACCURACY)) {
          loc.setAccuracy(values.getAsFloat(Waypoints.ACCURACY));
        }
        if (values.containsKey(Waypoints.ALTITUDE)) {
          loc.setAltitude(values.getAsDouble(Waypoints.ALTITUDE));
        }
        if (values.containsKey(Waypoints.BEARING)) {
          loc.setBearing(values.getAsFloat(Waypoints.BEARING));
        }
        waypointId = this.mDbHelper.insertWaypoint(trackId, segmentId, loc);
        //            Log.d( TAG, "Have inserted to segment "+segmentId+" with waypoint "+waypointId
        // );
        insertedUri = ContentUris.withAppendedId(uri, waypointId);
        break;
      case SEGMENTS:
        pathSegments = uri.getPathSegments();
        trackId = Integer.parseInt(pathSegments.get(1));
        segmentId = this.mDbHelper.toNextSegment(trackId);
        insertedUri = ContentUris.withAppendedId(uri, segmentId);
        break;
      case TRACKS:
        String name = (values == null) ? "" : values.getAsString(Tracks.NAME);
        trackId = this.mDbHelper.toNextTrack(name);
        insertedUri = ContentUris.withAppendedId(uri, trackId);
        break;
      default:
        Log.e(GPStrackingProvider.LOG_TAG, "Unable to match the URI:" + uri.toString());
        insertedUri = null;
        break;
    }
    return insertedUri;
  }
  @Override
  public Waypoint createWaypoint(Cursor cursor) {
    int idIndex = cursor.getColumnIndexOrThrow(WaypointsColumns._ID);
    int nameIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME);
    int descriptionIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION);
    int categoryIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY);
    int iconIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON);
    int trackIdIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID);
    int typeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE);
    int lengthIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH);
    int durationIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION);
    int startTimeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME);
    int startIdIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID);
    int stopIdIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID);
    int longitudeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE);
    int latitudeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE);
    int timeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME);
    int altitudeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE);
    int accuracyIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY);
    int speedIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED);
    int bearingIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING);
    int totalDistanceIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE);
    int totalTimeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME);
    int movingTimeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME);
    int maxSpeedIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED);
    int minElevationIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION);
    int maxElevationIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION);
    int elevationGainIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN);
    int minGradeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE);
    int maxGradeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE);

    Waypoint waypoint = new Waypoint();

    if (!cursor.isNull(idIndex)) {
      waypoint.setId(cursor.getLong(idIndex));
    }
    if (!cursor.isNull(nameIndex)) {
      waypoint.setName(cursor.getString(nameIndex));
    }
    if (!cursor.isNull(descriptionIndex)) {
      waypoint.setDescription(cursor.getString(descriptionIndex));
    }
    if (!cursor.isNull(categoryIndex)) {
      waypoint.setCategory(cursor.getString(categoryIndex));
    }
    if (!cursor.isNull(iconIndex)) {
      waypoint.setIcon(cursor.getString(iconIndex));
    }
    if (!cursor.isNull(trackIdIndex)) {
      waypoint.setTrackId(cursor.getLong(trackIdIndex));
    }
    if (!cursor.isNull(typeIndex)) {
      waypoint.setType(cursor.getInt(typeIndex));
    }
    if (!cursor.isNull(lengthIndex)) {
      waypoint.setLength(cursor.getFloat(lengthIndex));
    }
    if (!cursor.isNull(durationIndex)) {
      waypoint.setDuration(cursor.getLong(durationIndex));
    }
    if (!cursor.isNull(startIdIndex)) {
      waypoint.setStartId(cursor.getLong(startIdIndex));
    }
    if (!cursor.isNull(stopIdIndex)) {
      waypoint.setStopId(cursor.getLong(stopIdIndex));
    }

    Location location = new Location("");
    if (!cursor.isNull(longitudeIndex) && !cursor.isNull(latitudeIndex)) {
      location.setLongitude(((double) cursor.getInt(longitudeIndex)) / 1E6);
      location.setLatitude(((double) cursor.getInt(latitudeIndex)) / 1E6);
    }
    if (!cursor.isNull(timeIndex)) {
      location.setTime(cursor.getLong(timeIndex));
    }
    if (!cursor.isNull(altitudeIndex)) {
      location.setAltitude(cursor.getFloat(altitudeIndex));
    }
    if (!cursor.isNull(accuracyIndex)) {
      location.setAccuracy(cursor.getFloat(accuracyIndex));
    }
    if (!cursor.isNull(speedIndex)) {
      location.setSpeed(cursor.getFloat(speedIndex));
    }
    if (!cursor.isNull(bearingIndex)) {
      location.setBearing(cursor.getFloat(bearingIndex));
    }
    waypoint.setLocation(location);

    TripStatistics tripStatistics = new TripStatistics();
    boolean hasTripStatistics = false;
    if (!cursor.isNull(startTimeIndex)) {
      tripStatistics.setStartTime(cursor.getLong(startTimeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(totalDistanceIndex)) {
      tripStatistics.setTotalDistance(cursor.getFloat(totalDistanceIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(totalTimeIndex)) {
      tripStatistics.setTotalTime(cursor.getLong(totalTimeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(movingTimeIndex)) {
      tripStatistics.setMovingTime(cursor.getLong(movingTimeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(maxSpeedIndex)) {
      tripStatistics.setMaxSpeed(cursor.getFloat(maxSpeedIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(minElevationIndex)) {
      tripStatistics.setMinElevation(cursor.getFloat(minElevationIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(maxElevationIndex)) {
      tripStatistics.setMaxElevation(cursor.getFloat(maxElevationIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(elevationGainIndex)) {
      tripStatistics.setTotalElevationGain(cursor.getFloat(elevationGainIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(minGradeIndex)) {
      tripStatistics.setMinGrade(cursor.getFloat(minGradeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(maxGradeIndex)) {
      tripStatistics.setMaxGrade(cursor.getFloat(maxGradeIndex));
      hasTripStatistics = true;
    }

    if (hasTripStatistics) {
      waypoint.setTripStatistics(tripStatistics);
    }
    return waypoint;
  }
  private void updateCalculations(Uri trackUri) {
    mStarttime = -1;
    mEndtime = -1;
    mMaxSpeed = 0;
    mAverageActiveSpeed = 0;
    mMaxAltitude = 0;
    mMinAltitude = 0;
    mAscension = 0;
    mDistanceTraveled = 0f;
    mDuration = 0;
    long duration = 1;
    double ascension = 0;

    ContentResolver resolver = mContext.getContentResolver();

    Cursor waypointsCursor = null;
    try {
      waypointsCursor =
          resolver.query(
              Uri.withAppendedPath(trackUri, "waypoints"),
              new String[] {
                "max  (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")",
                "max  (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")",
                "min  (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")",
                "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")"
              },
              null,
              null,
              null);
      if (waypointsCursor.moveToLast()) {
        mMaxSpeed = waypointsCursor.getDouble(0);
        mMaxAltitude = waypointsCursor.getDouble(1);
        mMinAltitude = waypointsCursor.getDouble(2);
        long nrWaypoints = waypointsCursor.getLong(3);
        waypointsText = nrWaypoints + "";
      }
      waypointsCursor.close();
      waypointsCursor =
          resolver.query(
              Uri.withAppendedPath(trackUri, "waypoints"),
              new String[] {"avg  (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")"},
              Waypoints.TABLE + "." + Waypoints.SPEED + "  > ?",
              new String[] {"" + Constants.MIN_STATISTICS_SPEED},
              null);
      if (waypointsCursor.moveToLast()) {
        mAverageActiveSpeed = waypointsCursor.getDouble(0);
      }
    } finally {
      if (waypointsCursor != null) {
        waypointsCursor.close();
      }
    }
    Cursor trackCursor = null;
    try {
      trackCursor = resolver.query(trackUri, new String[] {Tracks.NAME}, null, null, null);
      if (trackCursor.moveToLast()) {
        tracknameText = trackCursor.getString(0);
      }
    } finally {
      if (trackCursor != null) {
        trackCursor.close();
      }
    }
    Cursor segments = null;
    Location lastLocation = null;
    Location lastAltitudeLocation = null;
    Location currentLocation = null;
    try {
      Uri segmentsUri = Uri.withAppendedPath(trackUri, "segments");
      segments = resolver.query(segmentsUri, new String[] {Segments._ID}, null, null, null);
      if (segments.moveToFirst()) {
        do {
          long segmentsId = segments.getLong(0);
          Cursor waypoints = null;
          try {
            Uri waypointsUri = Uri.withAppendedPath(segmentsUri, segmentsId + "/waypoints");
            waypoints =
                resolver.query(
                    waypointsUri,
                    new String[] {
                      Waypoints._ID,
                      Waypoints.TIME,
                      Waypoints.LONGITUDE,
                      Waypoints.LATITUDE,
                      Waypoints.ALTITUDE
                    },
                    null,
                    null,
                    null);
            if (waypoints.moveToFirst()) {
              do {
                if (mStarttime < 0) {
                  mStarttime = waypoints.getLong(1);
                }
                currentLocation = new Location(this.getClass().getName());
                currentLocation.setTime(waypoints.getLong(1));
                currentLocation.setLongitude(waypoints.getDouble(2));
                currentLocation.setLatitude(waypoints.getDouble(3));
                currentLocation.setAltitude(waypoints.getDouble(4));

                // Do no include obvious wrong 0.0 lat 0.0 long, skip to next value in while-loop
                if (currentLocation.getLatitude() == 0.0d
                    || currentLocation.getLongitude() == 0.0d) {
                  continue;
                }

                if (lastLocation != null) {
                  float travelPart = lastLocation.distanceTo(currentLocation);
                  long timePart = currentLocation.getTime() - lastLocation.getTime();
                  mDistanceTraveled += travelPart;
                  duration += timePart;
                }
                if (currentLocation.hasAltitude()) {
                  if (lastAltitudeLocation != null) {
                    if (currentLocation.getTime() - lastAltitudeLocation.getTime()
                        > 5 * 60 * 1000) // more then a 5m of climbing
                    {
                      if (currentLocation.getAltitude()
                          > lastAltitudeLocation.getAltitude() + 1) // more then 1m climb
                      {
                        ascension +=
                            currentLocation.getAltitude() - lastAltitudeLocation.getAltitude();
                        lastAltitudeLocation = currentLocation;
                      } else {
                        lastAltitudeLocation = currentLocation;
                      }
                    }
                  } else {
                    lastAltitudeLocation = currentLocation;
                  }
                }
                lastLocation = currentLocation;
                mEndtime = lastLocation.getTime();
              } while (waypoints.moveToNext());
              mDuration = mEndtime - mStarttime;
            }
          } finally {
            if (waypoints != null) {
              waypoints.close();
            }
          }
          lastLocation = null;
        } while (segments.moveToNext());
      }
    } finally {
      if (segments != null) {
        segments.close();
      }
    }
    double maxSpeed = mUnits.conversionFromMetersPerSecond(mMaxSpeed);
    double overallavgSpeedfl =
        mUnits.conversionFromMeterAndMiliseconds(mDistanceTraveled, mDuration);
    double avgSpeedfl = mUnits.conversionFromMeterAndMiliseconds(mDistanceTraveled, duration);
    double traveled = mUnits.conversionFromMeter(mDistanceTraveled);
    avgSpeedText = mUnits.formatSpeed(avgSpeedfl, true);
    overallavgSpeedText = mUnits.formatSpeed(overallavgSpeedfl, true);
    maxSpeedText = mUnits.formatSpeed(maxSpeed, true);
    distanceText = String.format("%.2f %s", traveled, mUnits.getDistanceUnit());
    ascensionText = String.format("%.0f %s", ascension, mUnits.getHeightUnit());
  }