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

The following examples show how to use android.location.Location#hasAccuracy() . 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: BackendFuser.java    From android_packages_apps_UnifiedNlp with Apache License 2.0 6 votes vote down vote up
/**
 * @return whether {@param lhs} is better than {@param rhs}
 */
@Override
public int compare(Location lhs, Location rhs) {
    if (lhs == rhs)
        return 0;
    if (lhs == null) {
        return 1;
    }
    if (rhs == null) {
        return -1;
    }
    if (!lhs.hasAccuracy()) {
        return 1;
    }
    if (!rhs.hasAccuracy()) {
        return -1;
    }
    if (rhs.getTime() > lhs.getTime() + SWITCH_ON_FRESHNESS_CLIFF_MS) {
        return 1;
    }
    if (lhs.getTime() > rhs.getTime() + SWITCH_ON_FRESHNESS_CLIFF_MS) {
        return -1;
    }
    return (int) (lhs.getAccuracy() - rhs.getAccuracy());
}
 
Example 2
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
private boolean isBetterLocation(Location prev, Location current) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean pref_altitude = prefs.getBoolean(SettingsFragment.PREF_ALTITUDE, SettingsFragment.DEFAULT_ALTITUDE);
    return (prev == null ||
            ((!pref_altitude || !prev.hasAltitude() || current.hasAltitude()) &&
                    (current.hasAccuracy() ? current.getAccuracy() : Float.MAX_VALUE) <
                            (prev.hasAccuracy() ? prev.getAccuracy() : Float.MAX_VALUE)));
}
 
Example 3
Source File: CommandGetLocationCoordinates.java    From SimpleSmsRemote with MIT License 6 votes vote down vote up
@Override
public void execute(Context context, CommandInstance commandInstance, CommandExecResult result)
        throws Exception {
    Location location = LocationUtils.GetLocation(context, 20000);
    if (location == null)
        throw new Exception("Location Request timed out");

    String locationDescription = String.format(Locale.ENGLISH, "%1$.4f %2$.4f",
            location.getLatitude(), location.getLongitude());
    String mapsLinkParam = String.format(Locale.ENGLISH, "%1$.4f,%2$.4f",
            location.getLatitude(), location.getLongitude());
    String mapsLink = "https://www.google.com/maps?q=" + mapsLinkParam;
    // get timestamp in RFC3339 format
    String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ")
            .format(new Date(location.getTime()));
    String accuracy = location.hasAccuracy()
            ? String.format(Locale.getDefault(), "%1$.0fm radius (68%% probability)", location.getAccuracy())
            : context.getString(R.string.unknown_accuracy);
    // see https://developer.android.com/reference/android/location/Location.html#getAccuracy()
    result.setCustomResultMessage(context.getString(
            R.string.result_msg_location_coordinates, locationDescription, timestamp, accuracy, mapsLink));
    result.setForceSendingResultSmsMessage(true);
}
 
Example 4
Source File: DatabaseHelper.java    From BackPackTrackII with GNU General Public License v3.0 6 votes vote down vote up
private ContentValues getLifelineLocation(long id, String name, Location location) throws JSONException {
    JSONObject jloc = new JSONObject();
    if (name != null)
        jloc.put("name", name);
    jloc.put("lat", location.getLatitude());
    jloc.put("lon", location.getLongitude());
    if (location.hasAltitude())
        jloc.put("alt", Math.round(location.getAltitude()));
    if (location.hasAccuracy())
        jloc.put("acc", Math.round(location.getAccuracy()));

    ContentValues cv = new ContentValues();
    cv.put("time", location.getTime());
    cv.put("source", mContext.getPackageName());
    cv.put("type", name == null ? "trackpoint" : "waypoint");
    cv.put("data", jloc.toString());
    cv.put("reference", Long.toString(id));
    return cv;
}
 
Example 5
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 6
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 7
Source File: BackendService.java    From AppleWifiNlpBackend with Apache License 2.0 5 votes vote down vote up
private synchronized Location calculate(Set<WiFi> wiFis) {
    if (!isConnected()) {
        return null;
    }
    Set<Location> locations = new HashSet<>();
    Set<String> unknown = new HashSet<>();
    for (WiFi wifi : wiFis) {
        Location location = database.get(wifi.getBssid());
        if (location != null) {
            if ((location.getTime() + THIRTY_DAYS) < System.currentTimeMillis()) {
                // Location is old, let's refresh it :)
                unknown.add(wifi.getBssid());
            }
            location.getExtras().putInt(LocationRetriever.EXTRA_SIGNAL_LEVEL, wifi.getRssi());
            if (location.hasAccuracy() && location.getAccuracy() != -1) {
                locations.add(location);
            }
        } else {
            unknown.add(wifi.getBssid());
        }
    }
    Log.d(TAG, "Found " + wiFis.size() + " wifis, of whom " + locations.size() + " with " +
            "location and " + unknown.size() + " unknown.");
    if (!unknown.isEmpty()) {
        if (toRetrieve == null) {
            toRetrieve = unknown;
        } else {
            toRetrieve.addAll(unknown);
        }
    }
    if (thread == null) {
        thread = new Thread(retrieveAction);
        thread.start();
    }
    return calculator.calculate(locations);
}
 
Example 8
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 9
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 10
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 11
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 12
Source File: Androzic.java    From Androzic with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onLocationChanged(final Location location, final boolean continous, final boolean geoid, final float smoothspeed, final float avgspeed)
{
	Log.d(TAG, "Location arrived");

	final long lastLocationMillis = location.getTime();

	if (angleMagnetic && lastLocationMillis - lastMagnetic >= magInterval)
	{
		GeomagneticField mag = new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(), (float) location.getAltitude(), System.currentTimeMillis());
		magneticDeclination = mag.getDeclination();
		lastMagnetic = lastLocationMillis;
	}

	Androzic.this.location[0] = location.getLatitude();
	Androzic.this.location[1] = location.getLongitude();

	shouldEnableFollowing = shouldEnableFollowing || lastKnownLocation == null;

	lastKnownLocation = location;
	gpsEnabled = gpsEnabled || LocationManager.GPS_PROVIDER.equals(location.getProvider());
	gpsContinous = continous;
	gpsGeoid = geoid;

	if (overlayManager.accuracyOverlay != null && location.hasAccuracy())
	{
		overlayManager.accuracyOverlay.setAccuracy(location.getAccuracy());
	}
}
 
Example 13
Source File: Positioning.java    From experimental-fall-detector-android-app with MIT License 5 votes vote down vote up
private double accuracy(Location location) {
    if (null != location && location.hasAccuracy()) {
        return (location.getAccuracy());
    } else {
        return (Double.POSITIVE_INFINITY);
    }
}
 
Example 14
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();
    }
}
 
Example 15
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 16
Source File: LocationValidator.java    From TowerCollector with Mozilla Public License 2.0 4 votes vote down vote up
public boolean hasRequiredAccuracy(Location location) {
    return (location.hasAccuracy() && location.getAccuracy() <= minAccuracy);
}
 
Example 17
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 18
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void handleUpdateLocation(Location location) {
    if (location.hasAccuracy()) {
        native_inject_location(location.getLatitude(), location.getLongitude(),
                location.getAccuracy());
    }
}
 
Example 19
Source File: MapSectionFragment.java    From satstat with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Called when a new location is found by a registered location provider.
 * Stores the location and updates GPS display and map view.
 */
public void onLocationChanged(Location location) {
	// some providers may report NaN for latitude and longitude:
	// if that happens, do not process this location and mark any previous
	// location from that provider as stale
	if (Double.isNaN(location.getLatitude()) || Double.isNaN(location.getLongitude())) {
		markLocationAsStale(providerLocations.get(location.getProvider()));
		applyLocationProviderStyle(this.getContext(), location.getProvider(), Const.LOCATION_PROVIDER_GRAY);
		return;
	}

	if (providerLocations.containsKey(location.getProvider()))
		providerLocations.put(location.getProvider(), new Location(location));

	LatLong latLong = new LatLong(location.getLatitude(), location.getLongitude());

	Circle circle = mapCircles.get(location.getProvider());
	Marker marker = mapMarkers.get(location.getProvider());

	if (circle != null) {
		circle.setLatLong(latLong);
		if (location.hasAccuracy()) {
			circle.setVisible(true);
			circle.setRadius(location.getAccuracy());
		} else {
			Log.d("MainActivity", "Location from " + location.getProvider() + " has no accuracy");
			circle.setVisible(false);
		}
	}

	if (marker != null) {
		marker.setLatLong(latLong);
		marker.setVisible(true);
	}

	applyLocationProviderStyle(this.getContext(), location.getProvider(), null);

	Runnable invalidator = providerInvalidators.get(location.getProvider());
	if (invalidator != null) {
		providerInvalidationHandler.removeCallbacks(invalidator);
		providerInvalidationHandler.postDelayed(invalidator, PROVIDER_EXPIRATION_DELAY);
	}

	// redraw, move locations into view and zoom out as needed
	if ((circle != null) || (marker != null) || (invalidator != null))
		updateMap();
}
 
Example 20
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
private void handlePassiveLocationUpdate(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Process passive location update
    Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
    Log.i(TAG, "Update passive location=" + location);
    if (location == null || (location.getLatitude() == 0.0 && location.getLongitude() == 0.0))
        return;

    // Filter inaccurate passive locations
    int pref_inaccurate = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_INACCURATE, SettingsFragment.DEFAULT_PASSIVE_INACCURATE));
    if (!location.hasAccuracy() || location.getAccuracy() > pref_inaccurate) {
        Log.i(TAG, "Filtering inaccurate passive location=" + location);
        return;
    }

    // Get last location
    Location lastLocation = LocationDeserializer.deserialize(prefs.getString(SettingsFragment.PREF_LAST_LOCATION, null));
    if (lastLocation == null) {
        Log.i(TAG, "Passive location without last location, location=" + location);
        return;
    }

    // Filter old locations
    if (location.getTime() <= lastLocation.getTime()) {
        Log.i(TAG, "Passive location is older than last location, location=" + location);
        return;
    }

    // Correct altitude
    correctAltitude(location, this);

    // Filter nearby passive locations
    int pref_nearby = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_NEARBY, SettingsFragment.DEFAULT_PASSIVE_NEARBY));
    if (Util.distance(lastLocation, location) < pref_nearby &&
            (lastLocation.hasAccuracy() ? lastLocation.getAccuracy() : Float.MAX_VALUE) <=
                    (location.hasAccuracy() ? location.getAccuracy() : Float.MAX_VALUE)) {
        Log.i(TAG, "Filtering nearby passive location=" + location);
        return;
    }

    float bchange = 0;
    double achange = 0;
    boolean update = false;

    // Handle bearing change
    if (location.hasBearing()) {
        int pref_bearing_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_BEARING, SettingsFragment.DEFAULT_PASSIVE_BEARING));
        bchange = Math.abs(lastLocation.getBearing() - location.getBearing());
        if (bchange > 180)
            bchange = 360 - bchange;
        if (!lastLocation.hasBearing() || bchange > pref_bearing_change) {
            Log.i(TAG, "Bearing changed to " + location.getBearing());
            update = true;
        }
    }

    // Handle altitude change
    if (location.hasAltitude()) {
        int pref_altitude_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_ALTITUDE, SettingsFragment.DEFAULT_PASSIVE_ALTITUDE));
        achange = Math.abs(lastLocation.getAltitude() - location.getAltitude());
        if (!lastLocation.hasAltitude() || achange > pref_altitude_change) {
            Log.i(TAG, "Altitude changed to " + location.getAltitude());
            update = true;
        }
    }

    if (update) {
        // Persist new location
        prefs.edit().putString(SettingsFragment.PREF_LAST_LOCATION, LocationSerializer.serialize(location)).apply();
        DatabaseHelper dh = null;
        try {
            dh = new DatabaseHelper(this);
            int altitude_type = (location.hasAltitude() ? ALTITUDE_GPS : ALTITUDE_NONE);
            dh.insertLocation(location, altitude_type, null).close();
        } finally {
            if (dh != null)
                dh.close();
        }

        // Feedback
        showStateNotification(this);
        if (Util.debugMode(this))
            Util.toast(getString(R.string.title_trackpoint) +
                    " " + getProviderName(location, this) +
                    " " + Math.round(bchange) +
                    "° / " + Math.round(achange) + "m", Toast.LENGTH_SHORT, this);
    }
}