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

The following examples show how to use android.location.Location#setExtras() . 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: BackgroundLocation.java    From background-geolocation-android with Apache License 2.0 6 votes vote down vote up
/**
 * Return android Location instance
 *
 * @return android.location.Location instance
 */
public Location getLocation() {
    Location l = new Location(provider);
    l.setLatitude(latitude);
    l.setLongitude(longitude);
    l.setTime(time);
    if (hasAccuracy) l.setAccuracy(accuracy);
    if (hasAltitude) l.setAltitude(altitude);
    if (hasSpeed) l.setSpeed(speed);
    if (hasBearing) l.setBearing(bearing);
    l.setExtras(extras);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        l.setElapsedRealtimeNanos(elapsedRealtimeNanos);
    }

    return l;
}
 
Example 2
Source File: BackendHelper.java    From android_packages_apps_UnifiedNlp with Apache License 2.0 6 votes vote down vote up
private void setLastLocation(Location location) {
    if (location == null || !location.hasAccuracy()) {
        return;
    }
    if (location.getExtras() == null) {
        location.setExtras(new Bundle());
    }
    location.getExtras().putString(LOCATION_EXTRA_BACKEND_PROVIDER, location.getProvider());
    location.getExtras().putString(LOCATION_EXTRA_BACKEND_COMPONENT,
            serviceIntent.getComponent().flattenToShortString());
    location.setProvider("network");
    if (!location.hasAccuracy()) {
        location.setAccuracy(50000);
    }
    if (location.getTime() <= 0) {
        location.setTime(System.currentTimeMillis());
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        updateElapsedRealtimeNanos(location);
    }
    Location noGpsLocation = new Location(location);
    noGpsLocation.setExtras(null);
    location.getExtras().putParcelable(LocationProviderBase.EXTRA_NO_GPS_LOCATION, noGpsLocation);
    lastLocation = location;
}
 
Example 3
Source File: RfEmitter.java    From DejaVu with GNU General Public License v3.0 5 votes vote down vote up
/**
 * User facing location value. Differs from internal one in that we don't report
 * locations that are guarded due to being new or moved.
 *
 * @return The coverage estimate for our RF emitter or null if we don't trust our
 * information.
 */
public  Location getLocation() {
    // If we have no observation of the emitter we ought not give a
    // position estimate based on it.
    if (mLastObservation == null)
        return null;

    // If we don't trust the location, we ought not give a position
    // estimate based on it.
    if ((trust < REQUIRED_TRUST) || (status == EmitterStatus.STATUS_BLACKLISTED))
        return null;

    // If we don't have a coverage estimate we will get back a null location
    Location location = _getLocation();
    if (location == null)
        return null;

    // If we are unbelievably close to null island, don't report location
    if (!BackendService.notNullIsland(location))
        return null;

    // Time tags based on time of most recent observation
    location.setTime(mLastObservation.getLastUpdateTimeMs());
    location.setElapsedRealtimeNanos(mLastObservation.getElapsedRealtimeNanos());

    Bundle extras = new Bundle();
    extras.putString(LOC_RF_TYPE, type.toString());
    extras.putString(LOC_RF_ID, id);
    extras.putInt(LOC_ASU,mLastObservation.getAsu());
    extras.putLong(LOC_MIN_COUNT, ourCharacteristics.minCount);
    location.setExtras(extras);
    return location;
}
 
Example 4
Source File: WeightedAverage.java    From DejaVu with GNU General Public License v3.0 5 votes vote down vote up
public Location result() {
    if (count < 1)
        return null;

    final Location location = new Location(BackendService.LOCATION_PROVIDER);

    location.setTime(timeMs);
    location.setElapsedRealtimeNanos(mElapsedRealtimeNanos);

    location.setLatitude(latEst.getMean());
    location.setLongitude(lonEst.getMean());

    //
    // Accuracy estimate is in degrees, convert to meters for output.
    // We calculate North-South and East-West independently, convert to a
    // circular radius by finding the length of the diagonal.
    //
    double sdMetersLat = latEst.getStdDev() * BackendService.DEG_TO_METER;
    double cosLat = Math.max(BackendService.MIN_COS, Math.cos(Math.toRadians(latEst.getMean())));
    double sdMetersLon = lonEst.getStdDev() * BackendService.DEG_TO_METER * cosLat;

    float acc = (float) Math.max(Math.sqrt((sdMetersLat*sdMetersLat)+(sdMetersLon*sdMetersLon)),MINIMUM_BELIEVABLE_ACCURACY);
    location.setAccuracy(acc);

    Bundle extras = new Bundle();
    extras.putLong("AVERAGED_OF", count);
    location.setExtras(extras);

    return location;
}
 
Example 5
Source File: Kalman.java    From DejaVu with GNU General Public License v3.0 5 votes vote down vote up
public synchronized Location getLocation() {
    Long timeMs = System.currentTimeMillis();
    final Location location = new Location(BackendService.LOCATION_PROVIDER);

    predict(timeMs);
    location.setTime(timeMs);
    location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    location.setLatitude(mLatTracker.getPosition());
    location.setLongitude(mLonTracker.getPosition());
    if (mAltTracker != null)
        location.setAltitude(mAltTracker.getPosition());

    float accuracy = (float) (mLatTracker.getAccuracy() * BackendService.DEG_TO_METER);
    if (accuracy < MIN_ACCURACY)
        accuracy = MIN_ACCURACY;
    location.setAccuracy(accuracy);

    // Derive speed from degrees/ms in lat and lon
    double latVeolocity = mLatTracker.getVelocity() * BackendService.DEG_TO_METER;
    double lonVeolocity = mLonTracker.getVelocity() * BackendService.DEG_TO_METER *
            Math.cos(Math.toRadians(location.getLatitude()));
    float speed = (float) Math.sqrt((latVeolocity*latVeolocity)+(lonVeolocity*lonVeolocity));
    location.setSpeed(speed);

    // Compute bearing only if we are moving. Report old bearing
    // if we are below our threshold for moving.
    if (speed > MOVING_THRESHOLD) {
        mBearing = (float) Math.toDegrees(Math.atan2(latVeolocity, lonVeolocity));
    }
    location.setBearing(mBearing);

    Bundle extras = new Bundle();
    extras.putLong("AVERAGED_OF", samples);
    location.setExtras(extras);

    return location;
}
 
Example 6
Source File: MockLocationProvider.java    From mockgeofix with Apache License 2.0 5 votes vote down vote up
protected void _simulate(double longitude, double latitude, double altitude, int satellites) {
    Location mockLocation = new Location(locationProviderName); // a string
    mockLocation.setLatitude(latitude);  // double
    mockLocation.setLongitude(longitude);
    mockLocation.setAltitude(altitude);
    if (satellites != -1) {
        Bundle bundle = new Bundle();
        bundle.putInt("satellites", satellites);
        mockLocation.setExtras(bundle);
    }
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setAccuracy(accuracy);
    _simulate(mockLocation);
}
 
Example 7
Source File: MockLocationProvider.java    From android_packages_apps_GmsCore with Apache License 2.0 5 votes vote down vote up
public void setLocation(Location mockLocation) {
    if (mockLocation.getExtras() == null) {
        mockLocation.setExtras(new Bundle());
    }
    mockLocation.getExtras().putBoolean(KEY_MOCK_LOCATION, false);
    this.mockLocation = mockLocation;
    this.changeListener.onLocationChanged();
}
 
Example 8
Source File: LocationSubjectTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void extras() {
  Bundle bundle = new Bundle();
  bundle.putInt("extra", 2);

  Location location = new Location(LocationManager.GPS_PROVIDER);
  location.setExtras(bundle);

  assertThat(location).extras().containsKey("extra");
  assertThat(location).extras().integer("extra").isEqualTo(2);
}
 
Example 9
Source File: WifiLocationDatabase.java    From AppleWifiNlpBackend with Apache License 2.0 5 votes vote down vote up
private Location getLocation(Cursor cursor) {
    Location location = new Location("database");
    Bundle extras = new Bundle();
    int i = cursor.getColumnIndex(FIELD_MAC);
    if (i != -1 && !cursor.isNull(i)) {
        extras.putString(LocationRetriever.EXTRA_MAC_ADDRESS, cursor.getString(i));
    }
    i = cursor.getColumnIndex(FIELD_LATITUDE);
    if (i != -1 && !cursor.isNull(i)) {
        location.setLatitude(cursor.getDouble(i));
    }
    i = cursor.getColumnIndex(FIELD_LONGITUDE);
    if (i != -1 && !cursor.isNull(i)) {
        location.setLongitude(cursor.getDouble(i));
    }
    i = cursor.getColumnIndex(FIELD_ALTITUDE);
    if (i != -1 && !cursor.isNull(i)) {
        location.setAltitude(cursor.getDouble(i));
    }
    i = cursor.getColumnIndex(FIELD_ACCURACY);
    if (i != -1 && !cursor.isNull(i)) {
        location.setAccuracy(cursor.getFloat(i));
    }
    i = cursor.getColumnIndex(FIELD_TIME);
    if (i != -1 && !cursor.isNull(i)) {
        location.setTime(cursor.getLong(i));
    }
    i = cursor.getColumnIndex(FIELD_VERIFIED);
    if (i != -1 && !cursor.isNull(i)) {
        extras.putLong(LocationRetriever.EXTRA_VERIFIED_TIME, cursor.getLong(i));
    }
    location.setExtras(extras);
    return location;
}
 
Example 10
Source File: NmeaParser.java    From Androzic with GNU General Public License v3.0 4 votes vote down vote up
private boolean updateTime(String time) {
    if (time.length() < 6) {
        return false;
    }
    if (mYear == -1) {
        // Since we haven't seen a day/month/year yet,
        // we can't construct a meaningful time stamp.
        // Clean up any old data.
        mLatitude = 0.0;
        mLongitude = 0.0;
        mHasAltitude = false;
        mHasBearing = false;
        mHasSpeed = false;
        mExtras = null;
        return false;
    }

    int hour, minute;
    float second;
    try {
        hour = Integer.parseInt(time.substring(0, 2));
        minute = Integer.parseInt(time.substring(2, 4));
        second = Float.parseFloat(time.substring(4, time.length()));
    } catch (NumberFormatException nfe) {
        Log.e(TAG, "Error parsing timestamp " + time);
        return false;
    }

    int isecond = (int) second;
    int millis = (int) ((second - isecond) * 1000);
    Calendar c = new GregorianCalendar(sUtcTimeZone);
    c.set(mYear, mMonth, mDay, hour, minute, isecond);
    long newTime = c.getTimeInMillis() + millis;

    if (mTime == -1) {
        mTime = 0;
        mBaseTime = newTime;
    }
    newTime -= mBaseTime;

    // If the timestamp has advanced, copy the temporary data
    // into a new Location
    if (newTime != mTime) {
        mNewWaypoint = true;
        mLocation = new Location(mName);
        mLocation.setTime(mTime);
        mLocation.setLatitude(mLatitude);
        mLocation.setLongitude(mLongitude);
        if (mHasAltitude) {
            mLocation.setAltitude(mAltitude);
        }
        if (mHasBearing) {
            mLocation.setBearing(mBearing);
        }
        if (mHasSpeed) {
            mLocation.setSpeed(mSpeed);
        }
        mLocation.setExtras(mExtras);
        mExtras = null;

        mTime = newTime;
        mHasAltitude = false;
        mHasBearing = false;
        mHasSpeed = false;
    }
    return true;
}
 
Example 11
Source File: LocationFudger.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Create a coarse location.
 *
 * <p>Two techniques are used: random offsets and snap-to-grid.
 *
 * <p>First we add a random offset. This mitigates against detecting
 * grid transitions. Without a random offset it is possible to detect
 * a users position very accurately when they cross a grid boundary.
 * The random offset changes very slowly over time, to mitigate against
 * taking many location samples and averaging them out.
 *
 * <p>Second we snap-to-grid (quantize). This has the nice property of
 * producing stable results, and mitigating against taking many samples
 * to average out a random offset.
 */
private Location createCoarseLocked(Location fine) {
    Location coarse = new Location(fine);

    // clean all the optional information off the location, because
    // this can leak detailed location information
    coarse.removeBearing();
    coarse.removeSpeed();
    coarse.removeAltitude();
    coarse.setExtras(null);

    double lat = coarse.getLatitude();
    double lon = coarse.getLongitude();

    // wrap
    lat = wrapLatitude(lat);
    lon = wrapLongitude(lon);

    // Step 1) apply a random offset
    //
    // The goal of the random offset is to prevent the application
    // from determining that the device is on a grid boundary
    // when it crosses from one grid to the next.
    //
    // We apply the offset even if the location already claims to be
    // inaccurate, because it may be more accurate than claimed.
    updateRandomOffsetLocked();
    // perform lon first whilst lat is still within bounds
    lon += metersToDegreesLongitude(mOffsetLongitudeMeters, lat);
    lat += metersToDegreesLatitude(mOffsetLatitudeMeters);
    if (D) Log.d(TAG, String.format("applied offset of %.0f, %.0f (meters)",
            mOffsetLongitudeMeters, mOffsetLatitudeMeters));

    // wrap
    lat = wrapLatitude(lat);
    lon = wrapLongitude(lon);

    // Step 2) Snap-to-grid (quantize)
    //
    // This is the primary means of obfuscation. It gives nice consistent
    // results and is very effective at hiding the true location
    // (as long as you are not sitting on a grid boundary, which
    // step 1 mitigates).
    //
    // Note we quantize the latitude first, since the longitude
    // quantization depends on the latitude value and so leaks information
    // about the latitude
    double latGranularity = metersToDegreesLatitude(mGridSizeInMeters);
    lat = Math.round(lat / latGranularity) * latGranularity;
    double lonGranularity = metersToDegreesLongitude(mGridSizeInMeters, lat);
    lon = Math.round(lon / lonGranularity) * lonGranularity;

    // wrap again
    lat = wrapLatitude(lat);
    lon = wrapLongitude(lon);

    // apply
    coarse.setLatitude(lat);
    coarse.setLongitude(lon);
    coarse.setAccuracy(Math.max(mAccuracyInMeters, coarse.getAccuracy()));

    if (D) Log.d(TAG, "fudged " + fine + " to " + coarse);
    return coarse;
}
 
Example 12
Source File: MapSectionFragment.java    From satstat with GNU General Public License v3.0 4 votes vote down vote up
public static void markLocationAsStale(Location location) {
	if (location.getExtras() == null)
		location.setExtras(new Bundle());
	location.getExtras().putBoolean(KEY_LOCATION_STALE, true);
}
 
Example 13
Source File: LocationHelper.java    From android_external_UnifiedNlpApi with Apache License 2.0 4 votes vote down vote up
public static Location create(String source, long time, Bundle extras) {
    Location location = create(source, time);
    location.setExtras(extras);
    return location;
}
 
Example 14
Source File: LocationHelper.java    From android_external_UnifiedNlpApi with Apache License 2.0 4 votes vote down vote up
public static Location create(String source, double latitude, double longitude, double altitude, float accuracy, Bundle extras) {
    Location location = create(source, latitude, longitude, altitude, accuracy);
    location.setExtras(extras);
    return location;
}
 
Example 15
Source File: LocationHelper.java    From android_external_UnifiedNlpApi with Apache License 2.0 4 votes vote down vote up
public static Location create(String source, double latitude, double longitude, float altitude, Bundle extras) {
    Location location = create(source, latitude, longitude, altitude);
    location.setExtras(extras);
    return location;
}
 
Example 16
Source File: BackendService.java    From wifi_backend with GNU General Public License v3.0 4 votes vote down vote up
private Location wiFiBasedLocation(@NonNull List<WifiAccessPoint> accessPoints) {
    if (accessPoints.isEmpty()) {
        return null;
    } else {
        Set<Location> locations = new HashSet<>(accessPoints.size());

        for (WifiAccessPoint accessPoint : accessPoints) {
            SimpleLocation result = database.getLocation(accessPoint.rfId());

            if (result != null) {
                Bundle extras = new Bundle();
                extras.putInt(Configuration.EXTRA_SIGNAL_LEVEL, accessPoint.level());

                Location location = result.toAndroidLocation();
                location.setExtras(extras);
                locations.add(location);
            }
        }

        if (locations.isEmpty()) {
            if (DEBUG) {
                Log.i(TAG, "WifiDBResolver.process(): No APs with known locations");
            }
            return null;
        } else {
            // Find largest group of AP locations. If we don't have at
            // least two near each other then we don't have enough
            // information to get a good location.
            locations = LocationUtil.culledAPs(locations, BackendService.this);

            if (locations == null || locations.size() < 2) {
                if (DEBUG) {
                    Log.i(TAG, "WifiDBResolver.process(): Insufficient number of WiFi hotspots to resolve location");
                }
                return null;
            } else {
                Location avgLoc = LocationUtil.weightedAverage("wifi", locations);

                if (avgLoc == null) {
                    if (DEBUG) {
                        Log.e(TAG, "Averaging locations did not work.");
                    }
                    return null;
                } else {
                    avgLoc.setTime(System.currentTimeMillis());
                    return avgLoc;
                }
            }
        }
    }
}
 
Example 17
Source File: LocationHelper.java    From android_external_UnifiedNlpApi with Apache License 2.0 4 votes vote down vote up
public static Location create(String source, long time, Bundle extras) {
    Location location = create(source, time);
    location.setExtras(extras);
    return location;
}
 
Example 18
Source File: LocationHelper.java    From android_external_UnifiedNlpApi with Apache License 2.0 4 votes vote down vote up
public static Location create(String source, double latitude, double longitude, double altitude, float accuracy, Bundle extras) {
    Location location = create(source, latitude, longitude, altitude, accuracy);
    location.setExtras(extras);
    return location;
}
 
Example 19
Source File: LocationHelper.java    From android_external_UnifiedNlpApi with Apache License 2.0 4 votes vote down vote up
public static Location create(String source, double latitude, double longitude, float altitude, Bundle extras) {
    Location location = create(source, latitude, longitude, altitude);
    location.setExtras(extras);
    return location;
}
 
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();
    }
}