/**
   * Creates the {@link ContentValues} for a {@link Location}.
   *
   * @param location the location
   * @param trackId the track id
   */
  private ContentValues createContentValues(Location location, long trackId) {
    ContentValues values = new ContentValues();
    values.put(TrackPointsColumns.TRACKID, trackId);
    values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6));
    values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6));

    // Hack for Samsung phones that don't properly populate the time field
    long time = location.getTime();
    if (time == 0) {
      time = System.currentTimeMillis();
    }
    values.put(TrackPointsColumns.TIME, time);
    if (location.hasAltitude()) {
      values.put(TrackPointsColumns.ALTITUDE, location.getAltitude());
    }
    if (location.hasAccuracy()) {
      values.put(TrackPointsColumns.ACCURACY, location.getAccuracy());
    }
    if (location.hasSpeed()) {
      values.put(TrackPointsColumns.SPEED, location.getSpeed());
    }
    if (location.hasBearing()) {
      values.put(TrackPointsColumns.BEARING, location.getBearing());
    }

    if (location instanceof MyTracksLocation) {
      MyTracksLocation myTracksLocation = (MyTracksLocation) location;
      if (myTracksLocation.getSensorDataSet() != null) {
        values.put(TrackPointsColumns.SENSOR, myTracksLocation.getSensorDataSet().toByteArray());
      }
    }
    return values;
  }
  ContentValues createContentValues(Waypoint waypoint) {
    ContentValues values = new ContentValues();

    // Value < 0 indicates no id is available
    if (waypoint.getId() >= 0) {
      values.put(WaypointsColumns._ID, waypoint.getId());
    }
    values.put(WaypointsColumns.NAME, waypoint.getName());
    values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription());
    values.put(WaypointsColumns.CATEGORY, waypoint.getCategory());
    values.put(WaypointsColumns.ICON, waypoint.getIcon());
    values.put(WaypointsColumns.TRACKID, waypoint.getTrackId());
    values.put(WaypointsColumns.TYPE, waypoint.getType());
    values.put(WaypointsColumns.LENGTH, waypoint.getLength());
    values.put(WaypointsColumns.DURATION, waypoint.getDuration());
    values.put(WaypointsColumns.STARTID, waypoint.getStartId());
    values.put(WaypointsColumns.STOPID, waypoint.getStopId());

    Location location = waypoint.getLocation();
    if (location != null) {
      values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6));
      values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6));
      values.put(WaypointsColumns.TIME, location.getTime());
      if (location.hasAltitude()) {
        values.put(WaypointsColumns.ALTITUDE, location.getAltitude());
      }
      if (location.hasAccuracy()) {
        values.put(WaypointsColumns.ACCURACY, location.getAccuracy());
      }
      if (location.hasSpeed()) {
        values.put(WaypointsColumns.SPEED, location.getSpeed());
      }
      if (location.hasBearing()) {
        values.put(WaypointsColumns.BEARING, location.getBearing());
      }
    }

    TripStatistics tripStatistics = waypoint.getTripStatistics();
    if (tripStatistics != null) {
      values.put(WaypointsColumns.STARTTIME, tripStatistics.getStartTime());
      values.put(WaypointsColumns.TOTALDISTANCE, tripStatistics.getTotalDistance());
      values.put(WaypointsColumns.TOTALTIME, tripStatistics.getTotalTime());
      values.put(WaypointsColumns.MOVINGTIME, tripStatistics.getMovingTime());
      values.put(WaypointsColumns.AVGSPEED, tripStatistics.getAverageSpeed());
      values.put(WaypointsColumns.AVGMOVINGSPEED, tripStatistics.getAverageMovingSpeed());
      values.put(WaypointsColumns.MAXSPEED, tripStatistics.getMaxSpeed());
      values.put(WaypointsColumns.MINELEVATION, tripStatistics.getMinElevation());
      values.put(WaypointsColumns.MAXELEVATION, tripStatistics.getMaxElevation());
      values.put(WaypointsColumns.ELEVATIONGAIN, tripStatistics.getTotalElevationGain());
      values.put(WaypointsColumns.MINGRADE, tripStatistics.getMinGrade());
      values.put(WaypointsColumns.MAXGRADE, tripStatistics.getMaxGrade());
    }
    return values;
  }
 private void updateNewLocation(Location location) {
   LocationProviderAdapter.newLocationAvailable(
       location.getLatitude(),
       location.getLongitude(),
       location.getTime() / 1000.0,
       location.hasAltitude(),
       location.getAltitude(),
       location.hasAccuracy(),
       location.getAccuracy(),
       location.hasBearing(),
       location.getBearing(),
       location.hasSpeed(),
       location.getSpeed());
 }
  @Implementation
  public void set(Location l) {
    time = l.getTime();
    provider = l.getProvider();
    latitude = l.getLatitude();
    longitude = l.getLongitude();
    accuracy = l.getAccuracy();
    bearing = l.getBearing();
    altitude = l.getAltitude();
    speed = l.getSpeed();

    hasAccuracy = l.hasAccuracy();
    hasAltitude = l.hasAltitude();
    hasBearing = l.hasBearing();
    hasSpeed = l.hasSpeed();
  }
 @Override
 // This sets fields longitude, latitude, altitude, hasLocationData, and
 // hasAltitude, then calls LocationSensor.LocationChanged(), alll in the
 // enclosing class LocationSensor.
 public void onLocationChanged(Location location) {
   lastLocation = location;
   longitude = location.getLongitude();
   latitude = location.getLatitude();
   // If the current location doesn't have altitude information, the prior
   // altitude reading is retained.
   if (location.hasAltitude()) {
     hasAltitude = true;
     altitude = location.getAltitude();
   }
   hasLocationData = true;
   LocationChanged(latitude, longitude, altitude);
 }
  public static void setGpsParameters(Parameters parameters, Location loc) {
    // Clear previous GPS location from the parameters.
    parameters.removeGpsData();

    // We always encode GpsTimeStamp
    parameters.setGpsTimestamp(System.currentTimeMillis() / 1000);

    // Set GPS location.
    if (loc != null) {
      double lat = loc.getLatitude();
      double lon = loc.getLongitude();
      boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);

      if (hasLatLon) {
        Log.d(TAG, "Set gps location");
        parameters.setGpsLatitude(lat);
        parameters.setGpsLongitude(lon);
        parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
        if (loc.hasAltitude()) {
          parameters.setGpsAltitude(loc.getAltitude());
        } else {
          // for NETWORK_PROVIDER location provider, we may have
          // no altitude information, but the driver needs it, so
          // we fake one.
          parameters.setGpsAltitude(0);
        }
        if (loc.getTime() != 0) {
          // Location.getTime() is UTC in milliseconds.
          // gps-timestamp is UTC in seconds.
          long utcTimeSeconds = loc.getTime() / 1000;
          parameters.setGpsTimestamp(utcTimeSeconds);
        }
      } else {
        loc = null;
      }
    }
  }
Exemple #7
0
  @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
  public static JSONObject location2Json(Location location) throws JSONException {
    JSONObject latLng = new JSONObject();
    latLng.put("lat", location.getLatitude());
    latLng.put("lng", location.getLongitude());

    JSONObject params = new JSONObject();
    params.put("latLng", latLng);

    if (VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      params.put("elapsedRealtimeNanos", location.getElapsedRealtimeNanos());
    } else {
      params.put("elapsedRealtimeNanos", 0);
    }
    params.put("time", location.getTime());
    /*
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date date = new Date(location.getTime());
    params.put("timeFormatted", format.format(date));
    */
    if (location.hasAccuracy()) {
      params.put("accuracy", location.getAccuracy());
    }
    if (location.hasBearing()) {
      params.put("bearing", location.getBearing());
    }
    if (location.hasAltitude()) {
      params.put("altitude", location.getAltitude());
    }
    if (location.hasSpeed()) {
      params.put("speed", location.getSpeed());
    }
    params.put("provider", location.getProvider());
    params.put("hashCode", location.hashCode());
    return params;
  }
  /**
   * Given a location fix, processes it and displays it in the table on the form.
   *
   * @param loc Location information
   */
  private void DisplayLocationInfo(Location loc) {
    Utilities.LogDebug("GpsMainActivity.DisplayLocationInfo");
    try {

      if (loc == null) {
        return;
      }

      TextView tvLatitude = (TextView) findViewById(R.id.txtLatitude);
      TextView tvLongitude = (TextView) findViewById(R.id.txtLongitude);
      TextView tvDateTime = (TextView) findViewById(R.id.txtDateTimeAndProvider);

      TextView tvAltitude = (TextView) findViewById(R.id.txtAltitude);

      TextView txtSpeed = (TextView) findViewById(R.id.txtSpeed);

      TextView txtSatellites = (TextView) findViewById(R.id.txtSatellites);
      TextView txtDirection = (TextView) findViewById(R.id.txtDirection);
      TextView txtAccuracy = (TextView) findViewById(R.id.txtAccuracy);
      String providerName = loc.getProvider();

      if (providerName.equalsIgnoreCase("gps")) {
        providerName = getString(R.string.providername_gps);
      } else {
        providerName = getString(R.string.providername_celltower);
      }

      tvDateTime.setText(
          new Date(Session.getLatestTimeStamp()).toLocaleString()
              + getString(R.string.providername_using, providerName));
      tvLatitude.setText(String.valueOf(loc.getLatitude()));
      tvLongitude.setText(String.valueOf(loc.getLongitude()));

      if (loc.hasAltitude()) {

        double altitude = loc.getAltitude();

        if (AppSettings.shouldUseImperial()) {
          tvAltitude.setText(
              String.valueOf(Utilities.MetersToFeet(altitude)) + getString(R.string.feet));
        } else {
          tvAltitude.setText(String.valueOf(altitude) + getString(R.string.meters));
        }

      } else {
        tvAltitude.setText(R.string.not_applicable);
      }

      if (loc.hasSpeed()) {

        float speed = loc.getSpeed();
        String unit;
        if (AppSettings.shouldUseImperial()) {
          if (speed > 1.47) {
            speed = speed * 0.6818f;
            unit = getString(R.string.miles_per_hour);

          } else {
            speed = Utilities.MetersToFeet(speed);
            unit = getString(R.string.feet_per_second);
          }
        } else {
          if (speed > 0.277) {
            speed = speed * 3.6f;
            unit = getString(R.string.kilometers_per_hour);
          } else {
            unit = getString(R.string.meters_per_second);
          }
        }

        txtSpeed.setText(String.valueOf(speed) + unit);

      } else {
        txtSpeed.setText(R.string.not_applicable);
      }

      if (loc.hasBearing()) {

        float bearingDegrees = loc.getBearing();
        String direction;

        direction = Utilities.GetBearingDescription(bearingDegrees, getApplicationContext());

        txtDirection.setText(
            direction
                + "("
                + String.valueOf(Math.round(bearingDegrees))
                + getString(R.string.degree_symbol)
                + ")");
      } else {
        txtDirection.setText(R.string.not_applicable);
      }

      if (!Session.isUsingGps()) {
        txtSatellites.setText(R.string.not_applicable);
        Session.setSatelliteCount(0);
      }

      if (loc.hasAccuracy()) {

        float accuracy = loc.getAccuracy();

        if (AppSettings.shouldUseImperial()) {
          txtAccuracy.setText(
              getString(
                  R.string.accuracy_within,
                  String.valueOf(Utilities.MetersToFeet(accuracy)),
                  getString(R.string.feet)));

        } else {
          txtAccuracy.setText(
              getString(
                  R.string.accuracy_within, String.valueOf(accuracy), getString(R.string.meters)));
        }

      } else {
        txtAccuracy.setText(R.string.not_applicable);
      }

    } catch (Exception ex) {
      SetStatus(getString(R.string.error_displaying, ex.getMessage()));
    }
  }
  /**
   * Called by {@link MainActivity} when a new location is found by the GPS location provider.
   * Stores the location and updates GPS display and map view.
   */
  public void onLocationChanged(Location location) {
    if (location.hasAccuracy()) {
      Float getAcc = (float) 0.0;
      if (mainActivity.prefUnitType) {
        getAcc = (float) (location.getAccuracy());
      } else {
        getAcc = (float) (location.getAccuracy() * (float) 3.28084);
      }
      gpsAccuracy.setText(String.format("%.0f", getAcc));
      gpsAccuracyUnit.setText(
          getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
    } else {
      gpsAccuracy.setText(getString(R.string.value_none));
      gpsAccuracyUnit.setText("");
    }

    if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_DECIMAL) {
      gpsCoordLayout.setVisibility(View.GONE);
      gpsLatLayout.setVisibility(View.VISIBLE);
      gpsLonLayout.setVisibility(View.VISIBLE);
      gpsLat.setText(
          String.format("%.5f%s", location.getLatitude(), getString(R.string.unit_degree)));
      gpsLon.setText(
          String.format("%.5f%s", location.getLongitude(), getString(R.string.unit_degree)));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_MIN) {
      gpsCoordLayout.setVisibility(View.GONE);
      gpsLatLayout.setVisibility(View.VISIBLE);
      gpsLonLayout.setVisibility(View.VISIBLE);
      double dec = location.getLatitude();
      double deg = (int) dec;
      double min = 60.0 * (dec - deg);
      gpsLat.setText(
          String.format(
              "%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
      dec = location.getLongitude();
      deg = (int) dec;
      min = 60.0 * (dec - deg);
      gpsLon.setText(
          String.format(
              "%.0f%s %.3f'", deg, getString(R.string.unit_degree), min + /*rounding*/ 0.0005));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_SEC) {
      gpsCoordLayout.setVisibility(View.GONE);
      gpsLatLayout.setVisibility(View.VISIBLE);
      gpsLonLayout.setVisibility(View.VISIBLE);
      double dec = location.getLatitude();
      double deg = (int) dec;
      double tmp = 60.0 * (dec - deg);
      double min = (int) tmp;
      double sec = 60.0 * (tmp - min);
      gpsLat.setText(
          String.format(
              "%.0f%s %.0f' %.1f\"",
              deg, getString(R.string.unit_degree), min, sec + /*rounding*/ 0.05));
      dec = location.getLongitude();
      deg = (int) dec;
      tmp = 60.0 * (dec - deg);
      min = (int) tmp;
      sec = 60.0 * (tmp - min);
      gpsLon.setText(
          String.format(
              "%.0f%s %.0f' %.1f\"",
              deg, getString(R.string.unit_degree), min, sec + /*rounding*/ 0.05));
    } else if (mainActivity.prefCoord == SettingsActivity.KEY_PREF_COORD_MGRS) {
      gpsLatLayout.setVisibility(View.GONE);
      gpsLonLayout.setVisibility(View.GONE);
      gpsCoordLayout.setVisibility(View.VISIBLE);
      gpsCoord.setText(
          new LatLng(location.getLatitude(), location.getLongitude())
              .toMGRSRef()
              .toString(MGRSRef.PRECISION_1M));
    }
    if (mainActivity.prefUtc) df.setTimeZone(TimeZone.getTimeZone("UTC"));
    else df.setTimeZone(TimeZone.getDefault());
    gpsTime.setText(df.format(new Date(location.getTime())));

    if (location.hasAltitude()) {
      Float getAltitude = (float) 0.0;
      if (mainActivity.prefUnitType) {
        getAltitude = (float) (location.getAltitude());
      } else {
        getAltitude = (float) (location.getAltitude() * (float) 3.28084);
      }
      gpsAlt.setText(String.format("%.0f", getAltitude));
      gpsAltUnit.setText(
          getString(((mainActivity.prefUnitType) ? R.string.unit_meter : R.string.unit_feet)));
      orDeclination.setText(
          String.format(
              "%.0f%s",
              new GeomagneticField(
                      (float) location.getLatitude(),
                      (float) location.getLongitude(),
                      (float) (getAltitude),
                      location.getTime())
                  .getDeclination(),
              getString(R.string.unit_degree)));
    } else {
      gpsAlt.setText(getString(R.string.value_none));
      gpsAltUnit.setText("");
      orDeclination.setText(getString(R.string.value_none));
    }

    if (location.hasBearing()) {
      gpsBearing.setText(
          String.format("%.0f%s", location.getBearing(), getString(R.string.unit_degree)));
      gpsOrientation.setText(
          MainActivity.formatOrientation(this.getContext(), location.getBearing()));
    } else {
      gpsBearing.setText(getString(R.string.value_none));
      gpsOrientation.setText(getString(R.string.value_none));
    }

    if (location.hasSpeed()) {
      Float getSpeed = (float) 0.0;
      if (mainActivity.prefUnitType) {
        getSpeed = (float) (location.getSpeed() * 3.6f);
      } else {
        getSpeed = (float) (location.getSpeed() * 3.6f * 2.23694f);
      }
      gpsSpeed.setText(String.format("%.0f", getSpeed));
      gpsSpeedUnit.setText(
          getString(((mainActivity.prefUnitType) ? R.string.unit_km_h : R.string.unit_mph)));
    } else {
      gpsSpeed.setText(getString(R.string.value_none));
      gpsSpeedUnit.setText("");
    }

    // note: getting number of sats in fix by looking for "satellites"
    // in location's extras doesn't seem to work, always returns 0 sats
  }
    public void onLocationChanged(Location loc) {
      /**
       * Hemos obtenido una nueva localización 1. Comprobar si es una localización válida 1.1. Que
       * no sea null. 1.2. Que tenga precisión suficiente. 2. Si la localización es válida. 2.1.
       * Enviar la localización al servidor OPEN GTS 2.2. Graba la posición en la base de datos.
       * 2.3. Comprobar el número de puntos en la db y si es superior a maxNumRegistrosEnDb entonces
       * hay que exportar los puntos al fichero de texto de la SDcard y luego borrar los registros
       * de la base de datos 3. Actualizar variables de "lastLocation" y los contadores de puntos
       * obtenidos, puntos enviados, puntos rechazados y puntos en la db 4. Enviar los datos a los
       * clientes UI registrados.
       */

      // Para poder obtener la hora

      GregorianCalendar greg = new GregorianCalendar(TimeZone.getTimeZone("Europe/Madrid"));
      DateFormat timestampFormat = new SimpleDateFormat("yyyyMMddHHmmss");
      String fechaHora = timestampFormat.format(greg.getTime());
      // La fecha y hora del sistema en el momento que hemos la posición

      // 1. Comprobar si es una localización válida
      // 1.1. Que no sea null.
      if (loc != null) {
        boolean pointIsRecorded = false;
        int cuantosRegistros;

        try {
          // 1.2. Que tenga precisión suficiente.

          // TODO, determinar si programamos que al estar en modo intensivo
          // la precisión (accuracy) se tenga que comprobar o cualquiera
          // nos vale
          // 1.2.1 Si estamos en modo intensivo, cualquier accuracy nos vale
          // De momento no pedimos que tenga al menos minAccuracyMeters

          // TODO, hay que deja el IF como sigue y quita el if (true)
          // if (loc.hasAccuracy()
          //		&& loc.getAccuracy() <= minAccuracyMeters) {

          // Para hacer debug en el emulador dejamos pasar todos los puntos
          if (true) {
            pointIsRecorded = true;

            // 2. Si la localización es válida.
            // 2.1. Enviar la localización al servidor OPEN GTS
            String url =
                "http://"
                    + getServerName()
                    + getGprmcName()
                    + "acct="
                    + getAccountName()
                    + "&"
                    + "dev="
                    + getDeviceName()
                    + "&"
                    + "gprmc="
                    + OpenGTSutils.GPRMCEncode(loc);

            Log.i(tag, "URL: " + url);

            AsyncHttpClient client = new AsyncHttpClient();
            client.get(
                url,
                new AsyncHttpResponseHandler() {
                  @Override
                  public void onStart() {
                    Log.i(tag, "AsyncHttpClient onStart");
                  }

                  @Override
                  public void onSuccess(String response) {
                    Log.i(tag, "AsyncHttpClient SUCCESS " + response);
                    cntEnviados++;
                  }

                  @Override
                  public void onFailure(Throwable e, String response) {
                    Log.i(tag, "AsyncHttpClient FAILURE " + response);
                  }

                  @Override
                  public void onFinish() {
                    Log.i(tag, "AsyncHttpClient onFinish");
                  }
                });

            // 2.2. Graba la posición en la base de datos.
            DbPointsManager punto =
                new DbPointsManager(
                    timestampFormat.format(loc.getTime()),
                    loc.getLatitude(),
                    loc.getLongitude(),
                    loc.hasAltitude() ? loc.getAltitude() : 0.0,
                    loc.hasAccuracy() ? loc.getAccuracy() : 0.0,
                    loc.hasSpeed() ? loc.getSpeed() : 0.0,
                    loc.hasBearing() ? loc.getBearing() : 0.0,
                    false);
            // TODO, de momento el ultimo campo "puntoEnviado", sera false, hasta que
            // incorporemos un sistema para poder controlar que puntos se han podido enviar
            // y cuales no.

            db.addDbPoint(punto);

            // Saber cuantos registros hay en la base de datos
            cuantosRegistros = db.getDbPointsCount();

            Log.d(tag, "Reg #: " + cuantosRegistros + " Max #: " + maxNumRegistrosEnDb);

            // * 2.3. Comprobar el número de puntos en la db y si es superior a maxNumRegistrosEnDb
            // *      entonces hay que exportar los puntos al fichero de texto de la SDcard y
            // *      luego borrar los registros de la base de datos
            if (cuantosRegistros > maxNumRegistrosEnDb) {
              if (db.doDbExport(deviceName) > 0) {
                // * 2.3.1 Se ha exportado los datos pues ahora borrar el
                // * 	   contenido de la tabla "points" de la base de datos
                int i;
                i = db.deleteDbPointAll();
                Log.d(tag, "Se borraron " + i + "PUNTOS");
              }
            }

            Log.i(tag, "addDbPoint: " + punto.toString());
          }

        } catch (Exception e) {
          Log.e(tag, e.toString());
        } finally {
          // Si estamos aqui algo ha ido mal así que ...
          /* Este código en principio no es necesario
          if (db.isOpen())
          	db.close();
          */
        }

        // Toast
        if (pointIsRecorded) {
          cntObtenidos++;
          /* TODO
          if (showingDebugToast)
          	Toast.makeText(
          			getBaseContext(),
          			"Location stored: \nLat: "
          					+ sevenSigDigits.format(loc
          							.getLatitude())
          					+ " \nLon: "
          					+ sevenSigDigits.format(loc
          							.getLongitude())
          					+ " \nAlt: "
          					+ (loc.hasAltitude() ? loc
          							.getAltitude() + "m" : "?")
          					+ "\nVel: "
          					+ (loc.hasSpeed() ? loc.getSpeed()
          							+ "m" : "?")
          					+ " \nAcc: "
          					+ (loc.hasAccuracy() ? loc
          							.getAccuracy() + "m" : "?"),
          			Toast.LENGTH_LONG).show();
          */
        } else {
          cntRechazados++;
          /* TODO
          if (showingDebugToast)
          	Toast.makeText(
          			getBaseContext(),
          			"Location not accurate enough: \nLat: "
          					+ sevenSigDigits.format(loc
          							.getLatitude())
          					+ " \nLon: "
          					+ sevenSigDigits.format(loc
          							.getLongitude())
          					+ " \nAlt: "
          					+ (loc.hasAltitude() ? loc
          							.getAltitude() + "m" : "?")
          					+ "\nVel: "
          					+ (loc.hasSpeed() ? loc.getSpeed()
          							+ "m" : "?")
          					+ " \nAcc: "
          					+ (loc.hasAccuracy() ? loc
          							.getAccuracy() + "m" : "?"),
          			Toast.LENGTH_LONG).show();
          */
        }
      }

      // 3. Actualizar  variables de "lastLocation" y
      //    los contadores de puntos obtenidos, puntos enviados, puntos rechazados

      // Poner la fecha en YYMMDD HH:MM:SS
      StringBuffer buf = new StringBuffer(timestampFormat.format(loc.getTime()));
      buf.insert(4, '-');
      buf.insert(7, '-');
      buf.insert(10, ' ');
      buf.insert(13, ':');
      buf.insert(16, ':');

      // buf.append('Z');

      setLastDateTime(buf.toString());

      setLastLatitude(String.format("%1.6f", loc.getLatitude()));

      setLastLongitude(String.format("%1.6f", loc.getLongitude()));

      setLastAccuracy((loc.hasAccuracy() ? String.format("%1.0f", loc.getAccuracy()) + "m" : "?"));

      setLastAltitude((loc.hasAltitude() ? String.format("%1.0f", loc.getAltitude()) + "m" : "?"));

      setLastSpeed((loc.hasSpeed() ? String.format("%1.0f", loc.getSpeed()) + "m/s" : "?"));

      setLastSpeed(
          getLastSpeed()
              + " "
              + (loc.hasSpeed() ? String.format("%1.0f", loc.getSpeed() * 3.6) + "km/s" : "?"));

      Bundle extras = loc.getExtras();
      if (extras != null) {
        setLastSatellites(
            extras.containsKey("satellites") ? extras.get("satellites").toString() : "0");
        Log.d(tag, "sat: " + getLastSatellites());
      } else Log.d(tag, "sat: extras es null");

      // Guardar el objeto de la última localización
      setLastLoc(loc);

      // Guardar el número de registros en la base de datos para luego actualizar el UI
      setLastPointCounter(db.getDbPointsCount());

      // 4. Enviar los datos a los clientes UI registrados.
      sendMessageToUI();
    }
  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());
  }
Exemple #12
0
  public void updateLayouts(float Azi, float zAngle, Location l) {
    /*
    if(l.hasAccuracy()) this.gpsIcon.disconnect();
    else gpsIcon.update(l.getAccuracy());
    */
    if (Azi != -1) {
      // Process the accelerometor stuff
      // Manages mobile orientation
      float leftArm = Azi - (xAngleWidth / 2);
      float rightArm = Azi + (xAngleWidth / 2);
      if (leftArm < 0) leftArm = leftArm + 360;
      if (rightArm > 360) rightArm = rightArm - 360;

      if (this.curLeftArm == -1) this.curLeftArm = leftArm;
      if (this.curRightArm == -1) this.curRightArm = rightArm;

      if (!(aChanger(curLeftArm, leftArm, (float) 0.05))) leftArm = this.curLeftArm;
      else this.curLeftArm = leftArm;
      if (!(aChanger(this.curRightArm, rightArm, (float) 0.05))) rightArm = this.curRightArm;
      else this.curRightArm = rightArm;

      if (leftArm < 0) leftArm = leftArm + 360;
      if (rightArm > 360) rightArm = rightArm - 360;

      // gere l'orientation du mobile en hauteur
      float upperArm = zAngle + (yAngleWidth / 2);
      float lowerArm = zAngle - (yAngleWidth / 2);

      if (this.curUpperArm == -1) this.curUpperArm = upperArm;
      if (this.curLowerArm == -1) this.curLowerArm = lowerArm;

      if (!(aChanger(this.curUpperArm, upperArm, (float) 0.05))) upperArm = this.curUpperArm;
      else this.curUpperArm = upperArm;
      if (!(aChanger(this.curLowerArm, lowerArm, (float) 0.05))) lowerArm = this.curLowerArm;
      else this.curLowerArm = lowerArm;

      Enumeration<ARSphericalView> e = getArViews().elements();

      if (getArViews().size() == 0) return;

      while (e.hasMoreElements()) {
        // If we have a location, and the view has one, update it's data
        try {
          ARSphericalView view = e.nextElement();
          // ------------
          if (view.isVisible()) {

            if (l != null && view.getLocation() != null) {
              float old_azi = view.getAzimuth();
              float old_incli = view.getInclination();
              float new_incli;
              if (aChanger(old_azi, l.bearingTo(view.getLocation()), (float) 0.05)) {
                view.setAzimuth((l.bearingTo(view.getLocation())) - 90);
              }
              if (view.getAzimuth() < 0) view.setAzimuth(360 + view.getAzimuth());
              if (l.hasAltitude() && view.getLocation().hasAltitude()) {
                new_incli =
                    (float)
                        Math.atan(
                            ((view.getLocation().getAltitude() - l.getAltitude())
                                / l.distanceTo(view.getLocation())));
                if (aChanger(old_incli, new_incli, (float) 0.05)) view.setInclination(new_incli);
              }
            }
          }

          //				if(!isVisibleX(leftArm, rightArm, view.azimuth))
          //				{
          //					view.visible = false;
          //					continue;
          //				}
          //				if(!isVisibleY(lowerArm, upperArm, view.inclination))
          //				{
          //					view.visible = false;
          //						continue;
          //				}
          //					view.setVisible(true);
          int tmp_x = (int) calcXvalue(leftArm, rightArm, view.getAzimuth());
          int tmp_y = (int) calcYvalue(lowerArm, upperArm, view.getInclination());

          if (view instanceof MagnitudePOI) {
            view.layout(
                (int) (((MagnitudePOI) view).getShiftX() + tmp_x),
                (int) (((MagnitudePOI) view).getShiftY() + tmp_y),
                (int)
                    ((((MagnitudePOI) view).getShiftX())
                        + tmp_x
                        + ((MagnitudePOI) view).getViewWidth()),
                (int)
                    (((MagnitudePOI) view).getShiftY()
                        + tmp_y
                        + ((MagnitudePOI) view).getViewHeight()));
          } else view.layout(tmp_x, tmp_y, tmp_x, tmp_y);
        } catch (Exception x) {
          Log.e("ArLayout", x.getMessage());
        }
      }
    }
    // 37.763557,-122.410719
  }