/**
   * 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;
  }
  protected void drawMyLocation(
      final Canvas canvas,
      final MapView mapView,
      final Location lastFix,
      final GeoPoint myLocation) {

    final Projection pj = mapView.getProjection();
    pj.toMapPixels(mMyLocation, mMapCoords);

    if (mDrawAccuracyEnabled) {
      final float radius = pj.metersToEquatorPixels(lastFix.getAccuracy());

      mCirclePaint.setAlpha(50);
      mCirclePaint.setStyle(Style.FILL);
      canvas.drawCircle(mMapCoords.x, mMapCoords.y, radius, mCirclePaint);

      mCirclePaint.setAlpha(150);
      mCirclePaint.setStyle(Style.STROKE);
      canvas.drawCircle(mMapCoords.x, mMapCoords.y, radius, mCirclePaint);
    }

    canvas.getMatrix(mMatrix);
    mMatrix.getValues(mMatrixValues);

    if (DEBUGMODE) {
      final float tx = (-mMatrixValues[Matrix.MTRANS_X] + 20) / mMatrixValues[Matrix.MSCALE_X];
      final float ty = (-mMatrixValues[Matrix.MTRANS_Y] + 90) / mMatrixValues[Matrix.MSCALE_Y];
      canvas.drawText("Lat: " + lastFix.getLatitude(), tx, ty + 5, mPaint);
      canvas.drawText("Lon: " + lastFix.getLongitude(), tx, ty + 20, mPaint);
      canvas.drawText("Cog: " + lastFix.getBearing(), tx, ty + 35, mPaint);
      canvas.drawText("Acc: " + lastFix.getAccuracy(), tx, ty + 50, mPaint);
      canvas.drawText("Kts: " + lastFix.getSpeed() / 1.94384449, tx, ty + 65, mPaint);
    }

    // TODO: read from compass if available for bearing
    if (lastFix.hasBearing()) {
      /*
       * Rotate the direction-Arrow according to the bearing we are driving. And draw it
       * to the canvas.
       */
      directionRotater.setRotate(
          lastFix.getBearing(), DIRECTION_ARROW_CENTER_X, DIRECTION_ARROW_CENTER_Y);

      directionRotater.postTranslate(-DIRECTION_ARROW_CENTER_X, -DIRECTION_ARROW_CENTER_Y);
      directionRotater.postScale(
          1 / mMatrixValues[Matrix.MSCALE_X], 1 / mMatrixValues[Matrix.MSCALE_Y]);
      directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
      canvas.drawBitmap(DIRECTION_ARROW, directionRotater, mPaint);
    } else {
      directionRotater.setTranslate(-NULLDIRECTION_ICON_CENTER_X, -NULLDIRECTION_ICON_CENTER_Y);
      directionRotater.postScale(
          1 / mMatrixValues[Matrix.MSCALE_X], 1 / mMatrixValues[Matrix.MSCALE_Y]);
      directionRotater.postTranslate(mMapCoords.x, mMapCoords.y);
      canvas.drawBitmap(NULLDIRECTION_ICON, directionRotater, mPaint);
    }
  }
  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;
  }
    @Override
    void updateLatLng(@NonNull Location location) {
      if (latLng == null) {
        // first location fix
        latLng = new LatLng(location);
        locationUpdateTimestamp = SystemClock.elapsedRealtime();
      }

      // updateLatLng timestamp
      long previousUpdateTimeStamp = locationUpdateTimestamp;
      locationUpdateTimestamp = SystemClock.elapsedRealtime();

      // calculate animation duration
      long locationUpdateDuration;
      if (previousUpdateTimeStamp == 0) {
        locationUpdateDuration = 0;
      } else {
        // TODO remove 10 * hack to multiply duration to workaround easing interpolation
        // (easeCamera)
        locationUpdateDuration = 10 * (locationUpdateTimestamp - previousUpdateTimeStamp);
      }

      // calculate interpolated location
      previousLocation = latLng;
      latLng = new LatLng(location);
      interpolatedLocation =
          new LatLng(
              (latLng.getLatitude() + previousLocation.getLatitude()) / 2,
              (latLng.getLongitude() + previousLocation.getLongitude()) / 2);

      // build new camera
      CameraPosition.Builder builder = new CameraPosition.Builder().target(interpolatedLocation);

      // add direction
      if (myBearingTrackingMode == MyBearingTracking.GPS) {
        if (location.hasBearing()) {
          builder.bearing(location.getBearing());
          gpsDirection = 0;
        }
      } else if (myBearingTrackingMode == MyBearingTracking.COMPASS) {
        if (!compassListener.isPaused()) {
          builder.bearing(compassListener.getCurrentDegree());
          compassDirection = 0;
        }
      }

      updateAccuracy(location);

      // animate to new camera
      mapboxMap.easeCamera(
          CameraUpdateFactory.newCameraPosition(builder.build()),
          (int) locationUpdateDuration,
          null);
    }
 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());
 }
    @Override
    void updateLatLng(@NonNull final Location location) {
      if (latLng == null) {
        // first location update
        latLng = new LatLng(location);
        locationUpdateTimestamp = SystemClock.elapsedRealtime();
      }

      // update LatLng location
      previousLocation = latLng;
      latLng = new LatLng(location);

      // update LatLng direction
      if (location.hasBearing()) {
        gpsDirection = clamp(location.getBearing() - (float) mapboxMap.getCameraPosition().bearing);
      }

      // update LatLng accuracy
      updateAccuracy(location);

      // calculate updateLatLng time + add some extra offset to improve animation
      long previousUpdateTimeStamp = locationUpdateTimestamp;
      locationUpdateTimestamp = SystemClock.elapsedRealtime();
      long locationUpdateDuration =
          (long) ((locationUpdateTimestamp - previousUpdateTimeStamp) * 1.2);

      // calculate interpolated entity
      interpolatedLocation =
          new LatLng(
              (latLng.getLatitude() + previousLocation.getLatitude()) / 2,
              (latLng.getLongitude() + previousLocation.getLongitude()) / 2);

      // animate changes
      if (locationChangeAnimator != null) {
        locationChangeAnimator.end();
        locationChangeAnimator = null;
      }

      locationChangeAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
      locationChangeAnimator.setDuration((long) (locationUpdateDuration * 1.2));
      locationChangeAnimator.addUpdateListener(
          new MarkerCoordinateAnimatorListener(this, previousLocation, interpolatedLocation));
      locationChangeAnimator.setInterpolator(new FastOutLinearInInterpolator());
      locationChangeAnimator.start();

      // use interpolated location as current location
      latLng = interpolatedLocation;
    }
  @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();
  }
Beispiel #8
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;
  }
Beispiel #9
0
  public void updateMap(Location location) {
    Log.i(TAG, " Holy Moley ..." + location.toString());
    UserObject o =
        new UserObject("user", "" + location.getLatitude(), "" + location.getLongitude());

    userInfo.enqueue(o);
    userInfo.enqueueLoc(location);
    Log.i(TAG, "new co-ordinates: ========> " + o.getLast_lat() + o.getLast_long());
    userSession.setCurrLat(location.getLatitude());
    userSession.setCurrLng(location.getLongitude());

    // To avoid the case where we don't have enough data points
    if (userInfo.size() > 1) {
      UserObject lastInfo = userInfo.dequeue();
      Location dest = userInfo.dequeueLoc();

      //            calcSpeed(location.getLatitude(), location.getLongitude(),
      //                        lastInfo.getLast_lat_double(), lastInfo.getLast_long_double());
      calcSpeed(location, dest);
    }

    // Update friends locations
    if (!userSession.friends.isEmpty()) {
      Enumeration e = userSession.friends.elements();
      while (e.hasMoreElements()) {
        Log.i(TAG, " next friend ");
        updateFriendMarker((UserObject) e.nextElement());
      }
    }

    if (location.hasBearing()) {
      gotoMyLocation(location.getLatitude(), location.getLongitude(), location.getBearing());
    } else {
      gotoMyLocation(location.getLatitude(), location.getLongitude(), 0f);
    }
  }
Beispiel #10
0
  /**
   * 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
  }
Beispiel #12
0
    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();
    }