Java Code Examples for android.location.Location#hasSpeed()

The following examples show how to use android.location.Location#hasSpeed() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void injectBestLocation(Location location) {
    int gnssLocationFlags = LOCATION_HAS_LAT_LONG |
            (location.hasAltitude() ? LOCATION_HAS_ALTITUDE : 0) |
            (location.hasSpeed() ? LOCATION_HAS_SPEED : 0) |
            (location.hasBearing() ? LOCATION_HAS_BEARING : 0) |
            (location.hasAccuracy() ? LOCATION_HAS_HORIZONTAL_ACCURACY : 0) |
            (location.hasVerticalAccuracy() ? LOCATION_HAS_VERTICAL_ACCURACY : 0) |
            (location.hasSpeedAccuracy() ? LOCATION_HAS_SPEED_ACCURACY : 0) |
            (location.hasBearingAccuracy() ? LOCATION_HAS_BEARING_ACCURACY : 0);

    double latitudeDegrees = location.getLatitude();
    double longitudeDegrees = location.getLongitude();
    double altitudeMeters = location.getAltitude();
    float speedMetersPerSec = location.getSpeed();
    float bearingDegrees = location.getBearing();
    float horizontalAccuracyMeters = location.getAccuracy();
    float verticalAccuracyMeters = location.getVerticalAccuracyMeters();
    float speedAccuracyMetersPerSecond = location.getSpeedAccuracyMetersPerSecond();
    float bearingAccuracyDegrees = location.getBearingAccuracyDegrees();
    long timestamp = location.getTime();
    native_inject_best_location(gnssLocationFlags, latitudeDegrees, longitudeDegrees,
            altitudeMeters, speedMetersPerSec, bearingDegrees, horizontalAccuracyMeters,
            verticalAccuracyMeters, speedAccuracyMetersPerSecond, bearingAccuracyDegrees,
            timestamp);
}
 
Example 2
Source File: BackgroundLocation.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
public static BackgroundLocation fromLocation(Location location) {
    BackgroundLocation l = new BackgroundLocation();

    l.provider = location.getProvider();
    l.latitude = location.getLatitude();
    l.longitude = location.getLongitude();
    l.time = location.getTime();
    l.accuracy = location.getAccuracy();
    l.speed = location.getSpeed();
    l.bearing = location.getBearing();
    l.altitude = location.getAltitude();
    l.hasAccuracy = location.hasAccuracy();
    l.hasAltitude = location.hasAltitude();
    l.hasSpeed = location.hasSpeed();
    l.hasBearing = location.hasBearing();
    l.extras = location.getExtras();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        l.elapsedRealtimeNanos = location.getElapsedRealtimeNanos();
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        l.setIsFromMockProvider(location.isFromMockProvider());
    }

    return l;
}
 
Example 3
Source File: LocationService.java    From FineGeotag with GNU General Public License v3.0 6 votes vote down vote up
public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jObject = new JsonObject();

    jObject.addProperty("Provider", src.getProvider());
    jObject.addProperty("Time", src.getTime());
    jObject.addProperty("Latitude", src.getLatitude());
    jObject.addProperty("Longitude", src.getLongitude());

    if (src.hasAltitude())
        jObject.addProperty("Altitude", src.getAltitude());

    if (src.hasSpeed())
        jObject.addProperty("Speed", src.getSpeed());

    if (src.hasAccuracy())
        jObject.addProperty("Accuracy", src.getAccuracy());

    if (src.hasBearing())
        jObject.addProperty("Bearing", src.getBearing());

    return jObject;
}
 
Example 4
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jObject = new JsonObject();

    jObject.addProperty("Provider", src.getProvider());
    jObject.addProperty("Time", src.getTime());
    jObject.addProperty("Latitude", src.getLatitude());
    jObject.addProperty("Longitude", src.getLongitude());

    if (src.hasAltitude())
        jObject.addProperty("Altitude", src.getAltitude());

    if (src.hasSpeed())
        jObject.addProperty("Speed", src.getSpeed());

    if (src.hasAccuracy())
        jObject.addProperty("Accuracy", src.getAccuracy());

    if (src.hasBearing())
        jObject.addProperty("Bearing", src.getBearing());

    return jObject;
}
 
Example 5
Source File: GpsServices.java    From SpeedMeter with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    data = MainActivity.getData();
    if (data.isRunning()){
        currentLat = location.getLatitude();
        currentLon = location.getLongitude();

        if (data.isFirstTime()){
            lastLat = currentLat;
            lastLon = currentLon;
            data.setFirstTime(false);
        }

        lastlocation.setLatitude(lastLat);
        lastlocation.setLongitude(lastLon);
        double distance = lastlocation.distanceTo(location);

        if (location.getAccuracy() < distance){
            data.addDistance(distance);

            lastLat = currentLat;
            lastLon = currentLon;
        }

        if (location.hasSpeed()) {
            data.setCurSpeed(location.getSpeed() * 3.6);
            if(location.getSpeed() == 0){
                new isStillStopped().execute();
            }
        }
        data.update();
        updateNotification(true);
    }
}
 
Example 6
Source File: LocationUpdatePacket.java    From Hauk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the packet.
 *
 * @param ctx      Android application context.
 * @param session  The session for which location is being updated.
 * @param location The updated location data obtained from GNSS/network sensors.
 */
protected LocationUpdatePacket(Context ctx, Session session, Location location, LocationProvider accuracy) {
    super(ctx, session.getServerURL(), session.getConnectionParameters(), Constants.URL_PATH_POST_LOCATION);
    setParameter(Constants.PACKET_PARAM_SESSION_ID, session.getID());

    if (session.getDerivableE2EKey() == null) {
        // If not using end-to-end encryption, send parameters in plain text.
        setParameter(Constants.PACKET_PARAM_LATITUDE, String.valueOf(location.getLatitude()));
        setParameter(Constants.PACKET_PARAM_LONGITUDE, String.valueOf(location.getLongitude()));
        setParameter(Constants.PACKET_PARAM_PROVIDER_ACCURACY, String.valueOf(accuracy.getMode()));
        setParameter(Constants.PACKET_PARAM_TIMESTAMP, String.valueOf(System.currentTimeMillis() / (double) TimeUtils.MILLIS_PER_SECOND));

        // Not all devices provide these parameters:
        if (location.hasSpeed()) setParameter(Constants.PACKET_PARAM_SPEED, String.valueOf(location.getSpeed()));
        if (location.hasAccuracy()) setParameter(Constants.PACKET_PARAM_ACCURACY, String.valueOf(location.getAccuracy()));
    } else {
        // We're using end-to-end encryption - generate an IV and encrypt all parameters.
        try {
            Cipher cipher = Cipher.getInstance(Constants.E2E_TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, session.getDerivableE2EKey().deriveSpec(), new SecureRandom());
            byte[] iv = cipher.getIV();
            setParameter(Constants.PACKET_PARAM_INIT_VECTOR, Base64.encodeToString(iv, Base64.DEFAULT));

            setParameter(Constants.PACKET_PARAM_LATITUDE, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getLatitude()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT));
            setParameter(Constants.PACKET_PARAM_LONGITUDE, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getLongitude()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT));
            setParameter(Constants.PACKET_PARAM_PROVIDER_ACCURACY, Base64.encodeToString(cipher.doFinal(String.valueOf(accuracy.getMode()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT));
            setParameter(Constants.PACKET_PARAM_TIMESTAMP, Base64.encodeToString(cipher.doFinal(String.valueOf(System.currentTimeMillis() / (double) TimeUtils.MILLIS_PER_SECOND).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT));

            // Not all devices provide these parameters:
            if (location.hasSpeed()) setParameter(Constants.PACKET_PARAM_SPEED, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getSpeed()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT));
            if (location.hasAccuracy()) setParameter(Constants.PACKET_PARAM_ACCURACY, Base64.encodeToString(cipher.doFinal(String.valueOf(location.getAccuracy()).getBytes(StandardCharsets.UTF_8)), Base64.DEFAULT));
        } catch (Exception e) {
            Log.e("Error was thrown when encrypting location data", e); //NON-NLS
        }
    }
}
 
Example 7
Source File: ExifInterfaceEx.java    From FineGeotag with GNU General Public License v3.0 5 votes vote down vote up
public void setLocation(Location location) {
    // Latitude
    double lat = location.getLatitude();
    this.setAttribute(TAG_GPS_LATITUDE_REF, lat > 0 ? "N" : "S");
    this.setAttribute(TAG_GPS_LATITUDE, DMS(lat));

    // Longitude
    double lon = location.getLongitude();
    this.setAttribute(TAG_GPS_LONGITUDE_REF, lon > 0 ? "E" : "W");
    this.setAttribute(TAG_GPS_LONGITUDE, DMS(lon));

    // Date/time
    Date date = new Date(location.getTime());
    this.setAttribute(TAG_GPS_DATESTAMP, new SimpleDateFormat("y:M:d").format(date));
    this.setAttribute(TAG_GPS_TIMESTAMP, new SimpleDateFormat("H:m:s").format(date));

    // Altitude
    if (location.hasAltitude()) {
        double altitude = location.getAltitude();
        this.setAttribute(TAG_GPS_ALTITUDE_REF, altitude > 0 ? "0" : "1");
        this.setAttribute(TAG_GPS_ALTITUDE, String.valueOf(Math.abs(altitude)));
    }

    // Speed
    if (location.hasSpeed()) {
        this.setAttribute("GPSSpeedRef", "K"); // Km/h
        this.setAttribute("GPSSpeed", String.valueOf(location.getSpeed() * 3600 / 1000));
    }
}
 
Example 8
Source File: SmsSenderService.java    From Locate-driver with GNU General Public License v3.0 5 votes vote down vote up
public void sendLocationMessage(String phoneNumber, Location location) {
    //Log.d(TAG, "sendLocationMessage()" + location.getAccuracy());
    Resources r = context.getResources();
    Boolean fused = isLocationFused(location);

    DecimalFormat latAndLongFormat = new DecimalFormat("#.######");

    String text = r.getString(fused ? R.string.approximate : R.string.accurate) + " location:\n";


    text += r.getString(R.string.accuracy) + " " + Math.round(location.getAccuracy()) + "m\n";
    text += r.getString(R.string.latitude) + " " + latAndLongFormat.format(location.getLatitude()) + "\n";
    text += r.getString(R.string.longitude) + " " + latAndLongFormat.format(location.getLongitude()) + "";

    if (location.hasSpeed()) {
        if (speedType == 0) {
            text += "\n" + r.getString(R.string.speed) + " " + ((int) convertMPStoKMH(location.getSpeed())) + "KM/H";
        } else {
            text += "\n" + r.getString(R.string.speed) + " " + ((int) convertMPStoMPH(location.getSpeed())) + "MPH";
        }
    }

    if (location.hasAltitude() && location.getAltitude() != 0) {
        text += "\n" + r.getString(R.string.altitude) + " " + ((int) location.getAltitude()) + "m";
    }

    SmsSenderService.this.sendSMS(phoneNumber, text);
}
 
Example 9
Source File: MyTracksProviderUtilsImpl.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: GearService.java    From WheelLogAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public void onLocationChanged(Location location) {
        if(bHasSpeed = location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasAltitude = location.hasAltitude())
            mAltitude = location.getAltitude();
        if(location.hasSpeed())
            mSpeed = location.getSpeed();
        if(bHasBearing = location.hasBearing())
            mBearing = location.getBearing();
        mLatitude = location.getLatitude();
        mLongitude = location.getLongitude();
        mTime = location.getTime();
//        transmitMessage(); Me lo he llevado a la rutina que se ejecuta de forma temporizada
    }
 
Example 11
Source File: LocationHelper.java    From ActivityDiary with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Called when the location has changed.
 * <p>
 * <p> There are no restrictions on the use of the supplied Location object.
 *
 * @param location The new location, as a Location object.
 */
@Override
public void onLocationChanged(Location location) {
    ContentValues values = new ContentValues();
    currentLocation = location;
    values.put(ActivityDiaryContract.DiaryLocation.TIMESTAMP, location.getTime());
    values.put(ActivityDiaryContract.DiaryLocation.LATITUDE, location.getLatitude());
    values.put(ActivityDiaryContract.DiaryLocation.LONGITUDE, location.getLongitude());
    if (location.hasAccuracy()) {
        values.put(ActivityDiaryContract.DiaryLocation.HACC, new Integer(Math.round(location.getAccuracy() * 10)));
    }
    if (location.hasSpeed()) {
        values.put(ActivityDiaryContract.DiaryLocation.SPEED, location.getSpeed());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (location.hasSpeedAccuracy()) {
                values.put(ActivityDiaryContract.DiaryLocation.SACC, new Integer(Math.round(location.getSpeedAccuracyMetersPerSecond() * 10)));
            }
        }
    }
    if (location.hasAltitude()) {
        values.put(ActivityDiaryContract.DiaryLocation.ALTITUDE, location.getAltitude());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (location.hasVerticalAccuracy()) {
                values.put(ActivityDiaryContract.DiaryLocation.VACC,  new Integer(Math.round(location.getVerticalAccuracyMeters() * 10)));
            }
        }
    }
    startInsert(0, null, ActivityDiaryContract.DiaryLocation.CONTENT_URI,
            values);

}
 
Example 12
Source File: GpsSearch.java    From Finder with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    if (no_accurate_coords && location.hasAccuracy() &&
            (location.getAccuracy() < Float.valueOf(sPref.getString(GPS_ACCURACY, GPS_ACCURACY_DEFAULT)))) {
        locMan.removeUpdates(locListen);  //will be disabled after first accurate coords
        sms_answer.append("lat:");
        sms_answer.append(String.format(Locale.US, "%.8f",location.getLatitude()));
        sms_answer.append(" ");
        sms_answer.append("lon:");
        sms_answer.append(String.format(Locale.US, "%.8f", location.getLongitude()));
        sms_answer.append(" ");
        if (location.hasAltitude()) {
            sms_answer.append("alt:");
            sms_answer.append(String.format(Locale.US, "%.0f", location.getAltitude()));
            sms_answer.append(" m ");
        }
        if (location.hasSpeed()) {
            sms_answer.append("vel:");
            sms_answer.append(String.format(Locale.US, "%.2f", location.getSpeed() * 3.6f));
            sms_answer.append(" km/h ");
        }
        if (location.hasBearing()) {
            sms_answer.append("az:");
            sms_answer.append(String.format(Locale.US, "%.0f", location.getBearing()));
            sms_answer.append(" ");
        }
        sms_answer.append("acc:");
        sms_answer.append(String.format(Locale.US, "%.0f", location.getAccuracy()));
        sms_answer.append("\n");
        sms_answer.append(gen_short_osm_url(location.getLatitude(), location.getLongitude(), OSM_ZOOM));
        sms_answer.append("\n");
        no_accurate_coords = false;
        start_send();
    } else {
        lastTrue = true;  //coords are ready but not enough precise, send them
        lastLocation = location;
    }
}
 
Example 13
Source File: MyTracksProviderUtilsImpl.java    From mytracks with Apache License 2.0 4 votes vote down vote up
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().ordinal());
  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());
    values.put(WaypointsColumns.CALORIE, tripStatistics.getCalorie());
  }
  
  values.put(WaypointsColumns.PHOTOURL, waypoint.getPhotoUrl());    
  return values;
}
 
Example 14
Source File: TripStatisticsUpdater.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Adds a location. TODO: This assume location has a valid time.
 * 
 * @param location the location
 * @param minRecordingDistance the min recording distance
 * @param calculateCalorie true means calculate calorie
 * @param activityType the activity type of current track which is used to
 *          calculate calorie
 * @param weight the weight to calculate calorie which is used to calculate
 *          calorie
 */
public void addLocation(Location location, int minRecordingDistance,
    boolean calculateCalorie, ActivityType activityType, double weight) {
  // Always update time
  updateTime(location.getTime());
  if (!LocationUtils.isValidLocation(location)) {
    // Either pause or resume marker
    if (location.getLatitude() == PAUSE_LATITUDE) {
      if (lastLocation != null && lastMovingLocation != null
          && lastLocation != lastMovingLocation) {
        currentSegment.addTotalDistance(lastMovingLocation.distanceTo(lastLocation));
      }
      tripStatistics.merge(currentSegment);
    }
    currentSegment = init(location.getTime());
    lastLocation = null;
    lastMovingLocation = null;
    elevationBuffer.reset();
    runBuffer.reset();
    gradeBuffer.reset();
    speedBuffer.reset();
    return;
  }
  currentSegment.updateLatitudeExtremities(location.getLatitude());
  currentSegment.updateLongitudeExtremities(location.getLongitude());

  double elevationDifference = location.hasAltitude() ? updateElevation(location.getAltitude())
      : 0.0;

  if (lastLocation == null || lastMovingLocation == null) {
    lastLocation = location;
    lastMovingLocation = location;
    return;
  }

  double movingDistance = lastMovingLocation.distanceTo(location);
  if (movingDistance < minRecordingDistance
      && (!location.hasSpeed() || location.getSpeed() < MAX_NO_MOVEMENT_SPEED)) {
    speedBuffer.reset();
    lastLocation = location;
    return;
  }
  long movingTime = location.getTime() - lastLocation.getTime();
  if (movingTime < 0) {
    lastLocation = location;
    return;
  }

  // Update total distance
  currentSegment.addTotalDistance(movingDistance);

  // Update moving time
  currentSegment.addMovingTime(movingTime);

  // Update grade
  double run = lastLocation.distanceTo(location);
  updateGrade(run, elevationDifference);

  // Update max speed
  if (location.hasSpeed() && lastLocation.hasSpeed()) {
    updateSpeed(
        location.getTime(), location.getSpeed(), lastLocation.getTime(), lastLocation.getSpeed());
  }
  
  if (calculateCalorie) {
    // Update calorie
    double calorie = CalorieUtils.getCalorie(lastMovingLocation, location,
        gradeBuffer.getAverage(), weight, activityType);
    currentSegment.addCalorie(calorie);
  }
  lastLocation = location;
  lastMovingLocation = location;
}
 
Example 15
Source File: StatsUtils.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the location values.
 * 
 * @param context the context
 * @param activity the activity for finding views. If null, the view cannot be
 *          null
 * @param view the containing view for finding views. If null, the activity
 *          cannot be null
 * @param location the location
 * @param isRecording true if recording
 */
public static void setLocationValues(
    Context context, Activity activity, View view, Location location, boolean isRecording) {
  boolean metricUnits = PreferencesUtils.isMetricUnits(context);
  boolean reportSpeed = PreferencesUtils.isReportSpeed(context);

  // Set speed/pace
  View speed = getView(activity, view, R.id.stats_speed);
  speed.setVisibility(isRecording ? View.VISIBLE : View.INVISIBLE);

  if (isRecording) {
    double value = isRecording && location != null && location.hasSpeed() ? location.getSpeed()
        : Double.NaN;
    setSpeed(context, speed, R.string.stats_speed, R.string.stats_pace, value, metricUnits,
        reportSpeed);
  }

  // Set elevation
  boolean showGradeElevation = PreferencesUtils.getBoolean(
      context, R.string.stats_show_grade_elevation_key,
      PreferencesUtils.STATS_SHOW_GRADE_ELEVATION_DEFAULT) && isRecording;
  View elevation = getView(activity, view, R.id.stats_elevation);
  elevation.setVisibility(showGradeElevation ? View.VISIBLE : View.GONE);

  if (showGradeElevation) {
    double altitude = location != null && location.hasAltitude() ? location.getAltitude()
        : Double.NaN;
    setElevationValue(context, elevation, -1, altitude, metricUnits);
  }

  // Set coordinate
  boolean showCoordinate = PreferencesUtils.getBoolean(
      context, R.string.stats_show_coordinate_key, PreferencesUtils.STATS_SHOW_COORDINATE_DEFAULT)
      && isRecording;
  View coordinateSeparator = getView(activity, view, R.id.stats_coordinate_separator);
  View coordinateContainer = getView(activity, view, R.id.stats_coordinate_container);

  if (coordinateSeparator != null) {
    coordinateSeparator.setVisibility(showCoordinate ? View.VISIBLE : View.GONE);
  }
  coordinateContainer.setVisibility(showCoordinate ? View.VISIBLE : View.GONE);

  if (showCoordinate) {
    double latitude = location != null ? location.getLatitude() : Double.NaN;
    double longitude = location != null ? location.getLongitude() : Double.NaN;
    setCoordinateValue(
        context, getView(activity, view, R.id.stats_latitude), R.string.stats_latitude, latitude);
    setCoordinateValue(context, getView(activity, view, R.id.stats_longitude),
        R.string.stats_longitude, longitude);
  }
}
 
Example 16
Source File: MapOverlay.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor for a potentially valid cached location.
 */
public CachedLocation(Location location) {
  this.valid = LocationUtils.isValidLocation(location);
  this.latLng = valid ? new LatLng(location.getLatitude(), location.getLongitude()) : null;
  this.speed = location.hasSpeed() ? location.getSpeed() * UnitConversions.MS_TO_KMH : -1.0;
}
 
Example 17
Source File: CsvTrackWriter.java    From mytracks with Apache License 2.0 4 votes vote down vote up
private String getSpeed(Location location) {
  return location.hasSpeed() ? SHORT_FORMAT.format(location.getSpeed()) : null;
}
 
Example 18
Source File: SmsSenderService.java    From Locate-driver with GNU General Public License v3.0 4 votes vote down vote up
public static boolean isLocationFused(Location location) {
    return !location.hasAltitude() || !location.hasSpeed() || location.getAltitude() == 0;
}
 
Example 19
Source File: InformationCollector.java    From open-rmbt with Apache License 2.0 4 votes vote down vote up
public static JSONObject fillBasicInfo(JSONObject object, Context ctx) throws JSONException
{
    object.put("plattform", PLATTFORM_NAME);
    object.put("os_version", android.os.Build.VERSION.RELEASE + "(" + android.os.Build.VERSION.INCREMENTAL
            + ")");
    object.put("api_level", String.valueOf(android.os.Build.VERSION.SDK_INT));
    object.put("device", android.os.Build.DEVICE);
    object.put("model", android.os.Build.MODEL);
    object.put("product", android.os.Build.PRODUCT);
    object.put("language", Locale.getDefault().getLanguage());
    object.put("timezone", TimeZone.getDefault().getID());
    object.put("softwareRevision", RevisionHelper.getVerboseRevision());
    PackageInfo pInfo = getPackageInfo(ctx);
    if (pInfo != null)
    {
        object.put("softwareVersionCode", pInfo.versionCode);
        object.put("softwareVersionName", pInfo.versionName);
    }
    object.put("type", at.alladin.rmbt.android.util.Config.RMBT_CLIENT_TYPE);
    
    addClientFeatures(object, ctx);
    
    if (BASIC_INFORMATION_INCLUDE_LOCATION) {
     Location loc = GeoLocation.getLastKnownLocation(ctx);
     if (loc != null) {
     JSONObject locationJson = new JSONObject();
      locationJson.put("lat", loc.getLatitude());
      locationJson.put("long", loc.getLongitude());
      locationJson.put("provider", loc.getProvider());
      if (loc.hasSpeed())
      	locationJson.put("speed", loc.getSpeed());
      if (loc.hasAltitude())
      	locationJson.put("altitude", loc.getAltitude());
      locationJson.put("age", System.currentTimeMillis() - loc.getTime()); //getElapsedRealtimeNanos() would be better, but require higher API-level
      if (loc.hasAccuracy())
      	locationJson.put("accuracy", loc.getAccuracy());
      if (loc.hasSpeed())
      	locationJson.put("speed", loc.getSpeed());
      /*
       *  would require API level 18
      if (loc.isFromMockProvider())
      	locationJson.put("mock",loc.isFromMockProvider());
      */
      object.put("location", locationJson);
     }
    }
    
    InformationCollector infoCollector = null;
    
    if (ctx instanceof RMBTMainActivity) {
    	Fragment curFragment = ((RMBTMainActivity) ctx).getCurrentFragment();
        if (curFragment != null) {
     	if (curFragment instanceof RMBTMainMenuFragment) {
     		infoCollector = ((RMBTMainMenuFragment) curFragment).getInformationCollector();
     	}
        }
    }

    if (BASIC_INFORMATION_INCLUDE_LAST_SIGNAL_ITEM && (infoCollector != null)) {
    	SignalItem signalItem = infoCollector.getLastSignalItem();
    	if (signalItem != null) {
    		object.put("last_signal_item", signalItem.toJson());
    	}
    	else {
    		object.put("last_signal_item", JSONObject.NULL);
    	}
    }

    return object;
}
 
Example 20
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void handleReportLocation(boolean hasLatLong, Location location) {
    if (location.hasSpeed()) {
        mItarSpeedLimitExceeded = location.getSpeed() > ITAR_SPEED_LIMIT_METERS_PER_SECOND;
    }

    if (mItarSpeedLimitExceeded) {
        Log.i(TAG, "Hal reported a speed in excess of ITAR limit." +
                "  GPS/GNSS Navigation output blocked.");
        if (mStarted) {
            mGnssMetrics.logReceivedLocationStatus(false);
        }
        return;  // No output of location allowed
    }

    if (VERBOSE) Log.v(TAG, "reportLocation " + location.toString());

    // It would be nice to push the elapsed real-time timestamp
    // further down the stack, but this is still useful
    location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    location.setExtras(mLocationExtras.getBundle());

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

    if (mStarted) {
        mGnssMetrics.logReceivedLocationStatus(hasLatLong);
        if (hasLatLong) {
            if (location.hasAccuracy()) {
                mGnssMetrics.logPositionAccuracyMeters(location.getAccuracy());
            }
            if (mTimeToFirstFix > 0) {
                int timeBetweenFixes = (int) (SystemClock.elapsedRealtime() - mLastFixTime);
                mGnssMetrics.logMissedReports(mFixInterval, timeBetweenFixes);
            }
        }
    }

    mLastFixTime = SystemClock.elapsedRealtime();
    // report time to first fix
    if (mTimeToFirstFix == 0 && hasLatLong) {
        mTimeToFirstFix = (int) (mLastFixTime - mFixRequestTime);
        if (DEBUG) Log.d(TAG, "TTFF: " + mTimeToFirstFix);
        if (mStarted) {
            mGnssMetrics.logTimeToFirstFixMilliSecs(mTimeToFirstFix);
        }

        // notify status listeners
        mListenerHelper.onFirstFix(mTimeToFirstFix);
    }

    if (mSingleShot) {
        stopNavigating();
    }

    if (mStarted && mStatus != LocationProvider.AVAILABLE) {
        // For devices that use framework scheduling, a timer may be set to ensure we don't
        // spend too much power searching for a location, when the requested update rate is slow.
        // As we just recievied a location, we'll cancel that timer.
        if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mFixInterval < NO_FIX_TIMEOUT) {
            mAlarmManager.cancel(mTimeoutIntent);
        }

        // send an intent to notify that the GPS is receiving fixes.
        Intent intent = new Intent(LocationManager.GPS_FIX_CHANGE_ACTION);
        intent.putExtra(LocationManager.EXTRA_GPS_ENABLED, true);
        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
        updateStatus(LocationProvider.AVAILABLE);
    }

    if (!hasCapability(GPS_CAPABILITY_SCHEDULING) && mStarted &&
            mFixInterval > GPS_POLLING_THRESHOLD_INTERVAL) {
        if (DEBUG) Log.d(TAG, "got fix, hibernating");
        hibernate();
    }
}