android.location.Location

Here are the examples of the java api class android.location.Location taken from open source projects.

1. SerializableLocation#getLocation()

Project: gpslogger
File: SerializableLocation.java
public Location getLocation() {
    Location loc = new Location(provider);
    loc.setAltitude(altitude);
    loc.setAccuracy((float) accuracy);
    loc.setBearing(bearing);
    loc.setLatitude(latitude);
    loc.setLongitude(longitude);
    loc.setSpeed(speed);
    loc.setProvider(provider);
    loc.setTime(time);
    return loc;
}

2. SimpleTest#testLocation()

Project: unmock-plugin
File: SimpleTest.java
@Test
public void testLocation() {
    Location loc = new Location("GPS");
    loc.setLongitude(50);
    loc.setLatitude(8);
    Location loc2 = new Location("GPS");
    loc2.setLongitude(50);
    loc2.setLatitude(9);
    assertEquals(110598.56, loc.distanceTo(loc2), 0.5);
}

3. SimpleTest#testLocation()

Project: unmock-plugin
File: SimpleTest.java
@Test
public void testLocation() {
    Location loc = new Location("GPS");
    loc.setLongitude(50);
    loc.setLatitude(8);
    Location loc2 = new Location("GPS");
    loc2.setLongitude(50);
    loc2.setLatitude(9);
    assertEquals(110598.56, loc.distanceTo(loc2), 0.5);
}

4. PGPS#getDistance()

Project: Protocoder
File: PGPS.java
@ProtoMethod(description = "Get the distance from two points", example = "")
@ProtoMethodParam(params = { "startLatitude", "starLongitude", "endLatitude", "endLongitude" })
public double getDistance(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
    float[] results = null;
    // Location.distanceBetween(startLatitude, startLongitude, endLatitude,
    // endLongitude, results);
    Location locationA = new Location("point A");
    locationA.setLatitude(startLatitude);
    locationA.setLongitude(startLongitude);
    Location locationB = new Location("point B");
    locationB.setLatitude(endLatitude);
    locationB.setLongitude(endLongitude);
    float distance = locationA.distanceTo(locationB);
    return distance;
}

5. SimulatorService#getNextGPSLocation()

Project: MozStumbler
File: SimulatorService.java
@Override
public Location getNextGPSLocation() {
    // a string
    Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
    mockLocation.setLatitude(mLat);
    mockLocation.setLongitude(mLon);
    // meters above sea level
    mockLocation.setAltitude(42.0);
    mockLocation.setAccuracy(5);
    mockLocation.setTime(System.currentTimeMillis());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    // This is rougly ~5m-ish.
    mLat += 0.00003;
    mLon += 0.00003;
    return mockLocation;
}

6. LegacyMotionSensorTest#getNextGPSLocation()

Project: MozStumbler
File: LegacyMotionSensorTest.java
public Location getNextGPSLocation() {
    // a string
    Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
    mockLocation.setLatitude(mLat);
    mockLocation.setLongitude(mLon);
    // meters above sea level
    mockLocation.setAltitude(42.0);
    mockLocation.setAccuracy(5);
    mockLocation.setTime(clock.currentTimeMillis());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mockLocation.setElapsedRealtimeNanos(clock.currentTimeMillis() * 1000000);
    }
    // This is rougly ~5m-ish.
    mLat += 0.00003;
    mLon += 0.00003;
    return mockLocation;
}

7. StepManager#newLocationOneStepFurther()

Project: droidar
File: StepManager.java
// Handler code
/**
	 * Takes a location and updates its position according to the step
	 * 
	 * @param l
	 * @param d
	 * @param bearing
	 * @return
	 */
public static Location newLocationOneStepFurther(Location l, double d, double bearing) {
    bearing = Math.toRadians(bearing);
    // m equatorial radius
    double R = 6378100;
    double lat1 = Math.toRadians(l.getLatitude());
    double lon1 = Math.toRadians(l.getLongitude());
    double dr = d / R;
    double lat2 = Math.asin(Math.sin(lat1) * Math.cos(dr) + Math.cos(lat1) * Math.sin(dr) * Math.cos(bearing));
    double lon2 = lon1 + Math.atan2(Math.sin(bearing) * Math.sin(d / R) * Math.cos(lat1), Math.cos(d / R) - Math.sin(lat1) * Math.sin(lat2));
    Location ret = new Location("LOCMOV");
    ret.setLatitude(Math.toDegrees(lat2));
    ret.setLongitude(Math.toDegrees(lon2));
    ret.setAccuracy((float) (2.0f * d));
    ret.setAltitude(0);
    ret.setTime(System.currentTimeMillis());
    return ret;
}

8. Utils#setMockLocation()

Project: android-utils
File: Utils.java
/**
     * Set Mock Location for test device. DDMS cannot be used to mock location on an actual device.
     * So this method should be used which forces the GPS Provider to mock the location on an actual
     * device.
     **/
public static void setMockLocation(Context ctx, double longitude, double latitude) {
    LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    locationManager.addTestProvider(LocationManager.GPS_PROVIDER, "requiresNetwork" == "", "requiresSatellite" == "", "requiresCell" == "", "hasMonetaryCost" == "", "supportsAltitude" == "", "supportsSpeed" == "", "supportsBearing" == "", android.location.Criteria.POWER_LOW, android.location.Criteria.ACCURACY_FINE);
    Location newLocation = new Location(LocationManager.GPS_PROVIDER);
    newLocation.setLongitude(longitude);
    newLocation.setLatitude(latitude);
    newLocation.setTime(new Date().getTime());
    newLocation.setAccuracy(500);
    locationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
    locationManager.setTestProviderStatus(LocationManager.GPS_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
    // http://jgrasstechtips.blogspot.it/2012/12/android-incomplete-location-object.html
    makeLocationObjectComplete(newLocation);
    locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, newLocation);
}

9. LocationUpdateReceiverTest#shouldReturnLocationFromSameProviderAndNotSignificantlyAccurateButRelativelyNew()

Project: PanicButton
File: LocationUpdateReceiverTest.java
@Test
public void shouldReturnLocationFromSameProviderAndNotSignificantlyAccurateButRelativelyNew() {
    Location oldLocation = location(NETWORK_PROVIDER, 12.0, 20.0, currentTimeMillis(), LESS_ACCURATE);
    Location lessAccurateButNewLocation = location(NETWORK_PROVIDER, 12.0, 20.0, offsetCurrentTimeBy(10), VERY_LESS_ACCURATE);
    Location diffMoreAccurateProviderLocation = location(GPS_PROVIDER, 12.0, 20.0, offsetCurrentTimeBy(20), VERY_LESS_ACCURATE - 10.0f);
    Location significantlyLessAccurateLocation = location(NETWORK_PROVIDER, 13.0, 20.0, offsetCurrentTimeBy(10), SIGNIFICANTLY_LESS_ACCURATE);
    locationUpdateReceiver.onReceive(context, getIntent(oldLocation));
    locationUpdateReceiver.onReceive(context, getIntent(lessAccurateButNewLocation));
    locationUpdateReceiver.onReceive(context, getIntent(diffMoreAccurateProviderLocation));
    locationUpdateReceiver.onReceive(context, getIntent(significantlyLessAccurateLocation));
    assertLocation(diffMoreAccurateProviderLocation);
}

10. LocationAdapterTest#testLocationAdaption()

Project: MozStumbler
File: LocationAdapterTest.java
@Test
public void testLocationAdaption() throws JSONException {
    JSONObject expected = getExpectedLocation();
    assertEquals(LocationAdapter.getLat(expected), LAT, DELTA);
    assertEquals(LocationAdapter.getLng(expected), LNG, DELTA);
    assertEquals(LocationAdapter.getAccuracy(expected), ACCURACY, DELTA);
    // a string
    Location roundTrip = new Location(LocationManager.GPS_PROVIDER);
    roundTrip.setAccuracy(ACCURACY);
    roundTrip.setLongitude(LNG);
    roundTrip.setLatitude(LAT);
    JSONObject actual = LocationAdapter.toJSON(roundTrip);
    assertEquals(LocationAdapter.getLat(actual), LAT, DELTA);
    assertEquals(LocationAdapter.getLng(actual), LNG, DELTA);
    assertEquals(LocationAdapter.getAccuracy(actual), ACCURACY, DELTA);
}

11. LocationMgrImpl#findLocation()

Project: mixare
File: LocationMgrImpl.java
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.mixare.mgr.location.LocationFinder#findLocation(android.content.Context
	 * )
	 */
public void findLocation() {
    // fallback for the case where GPS and network providers are disabled
    Location hardFix = new Location("reverseGeocoded");
    // Frangart, Eppan, Bozen, Italy
    hardFix.setLatitude(46.480302);
    hardFix.setLongitude(11.296005);
    hardFix.setAltitude(300);
    try {
        requestBestLocationUpdates();
        //temporary set the current location, until a good provider is found
        curLoc = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), true));
    } catch (Exception ex2) {
        curLoc = hardFix;
        mixContext.doPopUp(R.string.connection_GPS_dialog_text);
    }
}

12. LocationFieldTest#testSave()

Project: androrm
File: LocationFieldTest.java
public void testSave() {
    Location l = new Location(LocationManager.GPS_PROVIDER);
    l.setLatitude(1.0);
    l.setLongitude(2.0);
    BlankModel b = new BlankModel();
    b.setLocation(l);
    b.save(getContext());
    BlankModel b2 = Model.objects(getContext(), BlankModel.class).get(b.getId());
    Location l2 = b2.getLocation();
    assertEquals(1.0, l2.getLatitude());
    assertEquals(2.0, l2.getLongitude());
}

13. LocationUpdateReceiverTest#shouldReturnLocationWhichHasAlmostSameAccuracyAndRelativelyNew()

Project: PanicButton
File: LocationUpdateReceiverTest.java
@Test
public void shouldReturnLocationWhichHasAlmostSameAccuracyAndRelativelyNew() {
    Location oldLocation = location(NETWORK_PROVIDER, 12.0, 20.0, currentTimeMillis(), LESS_ACCURATE);
    long time = offsetCurrentTimeBy(10);
    Location newLocation = location(NETWORK_PROVIDER, 12.0, 20.0, time, ALMOST_SAME_AS_LESS_ACCURATE);
    Location newLocationClone = location(NETWORK_PROVIDER, 12.0, 20.0, time, ALMOST_SAME_AS_LESS_ACCURATE);
    locationUpdateReceiver.onReceive(context, getIntent(oldLocation));
    locationUpdateReceiver.onReceive(context, getIntent(newLocation));
    locationUpdateReceiver.onReceive(context, getIntent(newLocationClone));
    assertLocation(newLocation);
}

14. LocationUpdateReceiverTest#shouldReturnMoreAccurateLocation()

Project: PanicButton
File: LocationUpdateReceiverTest.java
@Test
public void shouldReturnMoreAccurateLocation() {
    Location oldLocation = location(NETWORK_PROVIDER, 12.0, 20.0, currentTimeMillis(), LESS_ACCURATE);
    Location newLocation = location(NETWORK_PROVIDER, 11.5, 20.0, offsetCurrentTimeBy(40), MORE_ACCURATE);
    Location newLocation1 = location(NETWORK_PROVIDER, 11.0, 20.0, offsetCurrentTimeBy(-20), LESS_ACCURATE);
    locationUpdateReceiver.onReceive(context, getIntent(oldLocation));
    locationUpdateReceiver.onReceive(context, getIntent(newLocation));
    locationUpdateReceiver.onReceive(context, getIntent(newLocation1));
    assertLocation(newLocation);
}

15. LocationUpdateReceiverTest#shouldReturnSignificantlyLatestLocation()

Project: PanicButton
File: LocationUpdateReceiverTest.java
@Test
public void shouldReturnSignificantlyLatestLocation() {
    Location oldLocation1 = location(NETWORK_PROVIDER, 12.0, 20.0, offsetCurrentTimeBy(-90), LESS_ACCURATE);
    Location oldLocation2 = location(NETWORK_PROVIDER, 10.0, 20.0, offsetCurrentTimeBy(-80), LESS_ACCURATE);
    Location newLocation = location(NETWORK_PROVIDER, 11.0, 20.0, currentTimeMillis(), LESS_ACCURATE);
    locationUpdateReceiver.onReceive(context, getIntent(oldLocation1));
    locationUpdateReceiver.onReceive(context, getIntent(newLocation));
    locationUpdateReceiver.onReceive(context, getIntent(oldLocation1));
    locationUpdateReceiver.onReceive(context, getIntent(oldLocation2));
    assertLocation(newLocation);
}

16. ReporterTest#getLocationIntent()

Project: MozStumbler
File: ReporterTest.java
public static Intent getLocationIntent(double lat, double lon) {
    if (lat == 0) {
        lat = 20;
    }
    if (lon == 0) {
        lon = 30;
    }
    Location location = new Location("mock");
    location.setLongitude(lat);
    location.setLatitude(lon);
    Intent i = new Intent(GPSScanner.ACTION_GPS_UPDATED);
    i.putExtra(Intent.EXTRA_SUBJECT, GPSScanner.SUBJECT_NEW_LOCATION);
    i.putExtra(GPSScanner.NEW_LOCATION_ARG_LOCATION, location);
    i.putExtra(GPSScanner.ACTION_ARG_TIME, System.currentTimeMillis());
    return i;
}

17. RequestTests#testExecutePlaceRequestWithLocationAndSearchText()

Project: astrid
File: RequestTests.java
@MediumTest
@LargeTest
public void testExecutePlaceRequestWithLocationAndSearchText() {
    TestSession session = openTestSessionWithSharedUser();
    Location location = new Location("");
    location.setLatitude(47.6204);
    location.setLongitude(-122.3491);
    Request request = Request.newPlacesSearchRequest(session, location, 1000, 5, "Starbucks", null);
    Response response = request.executeAndWait();
    assertNotNull(response);
    assertNull(response.getError());
    GraphMultiResult graphResult = response.getGraphObjectAs(GraphMultiResult.class);
    assertNotNull(graphResult);
    List<GraphObject> results = graphResult.getData();
    assertNotNull(results);
}

18. RequestTests#testExecutePlaceRequestWithLocation()

Project: astrid
File: RequestTests.java
@MediumTest
@LargeTest
public void testExecutePlaceRequestWithLocation() {
    TestSession session = openTestSessionWithSharedUser();
    Location location = new Location("");
    location.setLatitude(47.6204);
    location.setLongitude(-122.3491);
    Request request = Request.newPlacesSearchRequest(session, location, 5, 5, null, null);
    Response response = request.executeAndWait();
    assertNotNull(response);
    assertNull(response.getError());
    GraphMultiResult graphResult = response.getGraphObjectAs(GraphMultiResult.class);
    assertNotNull(graphResult);
    List<GraphObject> results = graphResult.getData();
    assertNotNull(results);
}

19. RequestTests#testCreatePlacesSearchRequestWithLocation()

Project: astrid
File: RequestTests.java
@SmallTest
@MediumTest
@LargeTest
public void testCreatePlacesSearchRequestWithLocation() {
    Location location = new Location("");
    location.setLatitude(47.6204);
    location.setLongitude(-122.3491);
    Request request = Request.newPlacesSearchRequest(null, location, 1000, 50, null, null);
    assertTrue(request != null);
    assertEquals(HttpMethod.GET, request.getHttpMethod());
    assertEquals("search", request.getGraphPath());
}

20. LocationManagerTest#shouldReturnLastKnownLocationForAProvider()

Project: robolectric
File: LocationManagerTest.java
@Test
public void shouldReturnLastKnownLocationForAProvider() throws Exception {
    assertNull(locationManager.getLastKnownLocation(NETWORK_PROVIDER));
    Location networkLocation = new Location(NETWORK_PROVIDER);
    Location gpsLocation = new Location(GPS_PROVIDER);
    shadowLocationManager.setLastKnownLocation(NETWORK_PROVIDER, networkLocation);
    shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, gpsLocation);
    assertSame(locationManager.getLastKnownLocation(NETWORK_PROVIDER), networkLocation);
    assertSame(locationManager.getLastKnownLocation(GPS_PROVIDER), gpsLocation);
}

21. LocationUtils#getLastKnownLocation()

Project: osmdroid
File: LocationUtils.java
/**
	 * Get the most recent location from the GPS or Network provider.
	 *
	 * @return return the most recent location, or null if there's no known location
	 */
public static Location getLastKnownLocation(final LocationManager pLocationManager) {
    if (pLocationManager == null) {
        return null;
    }
    final Location gpsLocation = getLastKnownLocation(pLocationManager, LocationManager.GPS_PROVIDER);
    final Location networkLocation = getLastKnownLocation(pLocationManager, LocationManager.NETWORK_PROVIDER);
    if (gpsLocation == null) {
        return networkLocation;
    } else if (networkLocation == null) {
        return gpsLocation;
    } else {
        // both are non-null - use the most recent
        if (networkLocation.getTime() > gpsLocation.getTime() + GPS_WAIT_TIME) {
            return networkLocation;
        } else {
            return gpsLocation;
        }
    }
}

22. LocationActivityTest#shouldReturnTheLatestLocation()

Project: MozStumbler
File: LocationActivityTest.java
@Test
public void shouldReturnTheLatestLocation() {
    LocationManager locationManager = (LocationManager) Robolectric.application.getSystemService(Context.LOCATION_SERVICE);
    ShadowLocationManager shadowLocationManager = shadowOf(locationManager);
    LocationGenerator lgen = new LocationGenerator();
    Location expectedLocation = lgen.next();
    // This would be a method on our SimulationContext
    locationActivity.setTestProviderLocation(LocationManager.GPS_PROVIDER, expectedLocation);
    Location actualLocation = locationActivity.latestLocation();
    assertEquals(expectedLocation, actualLocation);
}

23. LocationUtils#getLastKnownLocation()

Project: MozStumbler
File: LocationUtils.java
/**
     * Get the most recent location from the GPS or Network provider.
     *
     * @return return the most recent location, or null if there's no known location
     */
public static Location getLastKnownLocation(final LocationManager pLocationManager) {
    if (pLocationManager == null) {
        return null;
    }
    final Location gpsLocation = getLastKnownLocation(pLocationManager, LocationManager.GPS_PROVIDER);
    final Location networkLocation = getLastKnownLocation(pLocationManager, LocationManager.NETWORK_PROVIDER);
    if (gpsLocation == null) {
        return networkLocation;
    } else if (networkLocation == null) {
        return gpsLocation;
    } else {
        // both are non-null - use the most recent
        if (networkLocation.getTime() > gpsLocation.getTime() + GPS_WAIT_TIME) {
            return networkLocation;
        } else {
            return gpsLocation;
        }
    }
}

24. PlainTextFileLoggerTest#getCsvLine_LocationWithHdopPdopVdop_ReturnsCSVLine()

Project: gpslogger
File: PlainTextFileLoggerTest.java
@Test
public void getCsvLine_LocationWithHdopPdopVdop_ReturnsCSVLine() {
    PlainTextFileLogger plain = new PlainTextFileLogger(null);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(101).withAccuracy(41).withBearing(119).withSpeed(9).putExtra("satellites", 7).putExtra("HDOP", "LOOKATTHISHDOP!").build();
    String actual = plain.getCsvLine(loc, "2011-09-17T18:45:33Z");
    String expected = "2011-09-17T18:45:33Z,12.193000,19.111000,101.0,41.0,119.0,9.0,7,MOCK,LOOKATTHISHDOP!,,,,,\n";
    assertThat("CSV line with HDOP", actual, is(expected));
    Location loc2 = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(101).withAccuracy(41).withBearing(119).withSpeed(9).putExtra("satellites", 7).putExtra("HDOP", "LOOKATTHISHDOP!").putExtra("VDOP", "392.13").putExtra("PDOP", "Papepeodpe").build();
    actual = plain.getCsvLine(loc2, "2011-09-17T18:45:33Z");
    expected = "2011-09-17T18:45:33Z,12.193000,19.111000,101.0,41.0,119.0,9.0,7,MOCK,LOOKATTHISHDOP!,392.13,Papepeodpe,,,\n";
    assertThat("CSV line with HDOP PDOP VDOP", actual, is(expected));
}

25. BackendHelper#setLastLocation()

Project: android_packages_apps_UnifiedNlp
File: BackendHelper.java
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;
}

26. BackendFuser#mergeLocations()

Project: android_packages_apps_UnifiedNlp
File: BackendFuser.java
private Location mergeLocations(List<Location> locations) {
    Collections.sort(locations, LocationComparator.INSTANCE);
    if (locations.isEmpty() || locations.get(0) == null)
        return null;
    if (locations.size() == 1)
        return locations.get(0);
    Location location = new Location(locations.get(0));
    ArrayList<Location> backendResults = new ArrayList<Location>();
    for (Location backendResult : locations) {
        if (locations.get(0) == backendResult)
            continue;
        if (backendResult != null)
            backendResults.add(backendResult);
    }
    if (!backendResults.isEmpty()) {
        location.getExtras().putParcelableArrayList(LOCATION_EXTRA_OTHER_BACKENDS, backendResults);
    }
    return location;
}

27. WifiReceiver#getScanPeriod()

Project: wigle-wifi-wardriving
File: WifiReceiver.java
public long getScanPeriod() {
    final SharedPreferences prefs = mainActivity.getSharedPreferences(ListFragment.SHARED_PREFS, 0);
    String scanPref = ListFragment.PREF_SCAN_PERIOD;
    long defaultRate = MainActivity.SCAN_DEFAULT;
    // if over 5 mph
    Location location = null;
    final GPSListener gpsListener = mainActivity.getGPSListener();
    if (gpsListener != null) {
        location = gpsListener.getLocation();
    }
    if (location != null && location.getSpeed() >= 2.2352f) {
        scanPref = ListFragment.PREF_SCAN_PERIOD_FAST;
        defaultRate = MainActivity.SCAN_FAST_DEFAULT;
    } else if (location == null || location.getSpeed() < 0.1f) {
        scanPref = ListFragment.PREF_SCAN_PERIOD_STILL;
        defaultRate = MainActivity.SCAN_STILL_DEFAULT;
    }
    return prefs.getLong(scanPref, defaultRate);
}

28. SocializeApi#setLocation()

Project: socialize-sdk-android
File: SocializeApi.java
protected void setLocation(SocializeAction action) {
    Location location = null;
    if (locationProvider != null) {
        location = locationProvider.getLastKnownLocation();
    }
    if (location != null) {
        action.setLon(location.getLongitude());
        action.setLat(location.getLatitude());
    }
    SocializeSession session = Socialize.getSocialize().getSession();
    if (session != null) {
        UserSettings settings = session.getUserSettings();
        if (settings != null) {
            action.setLocationShared(settings.isLocationEnabled());
        }
    }
}

29. SensorCollector#start()

Project: sensor-data-collection-library
File: SensorCollector.java
/**
   * Starts the collector. Sensors and wifi scan passes will be activated, and
   * their results will be written through to the given log. Calling close()
   * will stop the collection and close the log.
   */
public synchronized void start() {
    expectNotClosed();
    // record the last known location on survey start, so that we have
    // at least some idea of the location of the survey.
    String p = locationManager.getBestProvider(new Criteria(), true);
    Location loc = p != null ? locationManager.getLastKnownLocation(p) : null;
    if (loc != null) {
        log.logLastKnownPosition(loc);
    }
    startCollectors();
    isStarted = true;
}

30. LocationHelper#getLastKnownLocation()

Project: RxAndroidBootstrap
File: LocationHelper.java
public static Location getLastKnownLocation(Context context) {
    LocationManager mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}

31. AutoPauseTriggerTest#shouldNotSetPauseIfLoosingGps()

Project: runnerup
File: AutoPauseTriggerTest.java
@Test
public void shouldNotSetPauseIfLoosingGps() {
    float autoPauseAfterSeconds = 1;
    float autoPauseMinSpeed = 10;
    Location location = mock(Location.class);
    when(location.getTime()).thenReturn(1000L);
    Workout workout = mock(Workout.class);
    when(workout.getLastKnownLocation()).thenReturn(location);
    when(workout.getSpeed((Scope) any())).thenReturn(9d);
    AutoPauseTrigger sut = new AutoPauseTrigger(autoPauseAfterSeconds, autoPauseMinSpeed);
    sut.onTick(workout);
    sut.onTick(workout);
    when(workout.getSpeed((Scope) any())).thenReturn(11d);
    when(location.getTime()).thenReturn(5000L);
    sut.onTick(workout);
    verify(workout, never()).onPause(workout);
}

32. AutoPauseTriggerTest#shouldSetResumeIfSpeedIsHigh()

Project: runnerup
File: AutoPauseTriggerTest.java
@Test
public void shouldSetResumeIfSpeedIsHigh() {
    float autoPauseAfterSeconds = 1;
    float autoPauseMinSpeed = 10;
    Location location = mock(Location.class);
    when(location.getTime()).thenReturn(1000L);
    Workout workout = mock(Workout.class);
    when(workout.getLastKnownLocation()).thenReturn(location);
    when(workout.getSpeed((Scope) any())).thenReturn(9d);
    AutoPauseTrigger sut = new AutoPauseTrigger(autoPauseAfterSeconds, autoPauseMinSpeed);
    sut.onTick(workout);
    when(location.getTime()).thenReturn(3000L);
    sut.onTick(workout);
    when(workout.getSpeed((Scope) any())).thenReturn(11d);
    when(location.getTime()).thenReturn(5000L);
    sut.onTick(workout);
    verify(workout).onResume(workout);
}

33. AutoPauseTriggerTest#shouldNotSetPauseIfSpeedIsHigh()

Project: runnerup
File: AutoPauseTriggerTest.java
@Test
public void shouldNotSetPauseIfSpeedIsHigh() {
    float autoPauseAfterSeconds = 1;
    float autoPauseMinSpeed = 10;
    Location location = mock(Location.class);
    when(location.getTime()).thenReturn(1000L);
    Workout workout = mock(Workout.class);
    when(workout.getLastKnownLocation()).thenReturn(location);
    when(workout.getSpeed((Scope) any())).thenReturn(11d);
    AutoPauseTrigger sut = new AutoPauseTrigger(autoPauseAfterSeconds, autoPauseMinSpeed);
    sut.onTick(workout);
    when(location.getTime()).thenReturn(3000L);
    sut.onTick(workout);
    verify(workout, never()).onPause(workout);
}

34. AutoPauseTriggerTest#shouldSetPauseIfSpeedIsLow()

Project: runnerup
File: AutoPauseTriggerTest.java
@Test
public void shouldSetPauseIfSpeedIsLow() {
    float autoPauseAfterSeconds = 1;
    float autoPauseMinSpeed = 10;
    Location location = mock(Location.class);
    when(location.getTime()).thenReturn(1000L);
    Workout workout = mock(Workout.class);
    when(workout.getLastKnownLocation()).thenReturn(location);
    when(workout.getSpeed((Scope) any())).thenReturn(9d);
    AutoPauseTrigger sut = new AutoPauseTrigger(autoPauseAfterSeconds, autoPauseMinSpeed);
    sut.onTick(workout);
    when(location.getTime()).thenReturn(3000L);
    sut.onTick(workout);
    verify(workout).onPause(workout);
}

35. AutoPauseTrigger#HandleAutoPause()

Project: runnerup
File: AutoPauseTrigger.java
private void HandleAutoPause(Workout workout) {
    Location lastLocation = workout.getLastKnownLocation();
    Double currentSpeed = workout.getSpeed(Scope.CURRENT);
    if (currentSpeed == null)
        return;
    if (currentSpeed < mAutoPauseMinSpeed) {
        if (!mIsAutoPaused && mHasStopped && (lastLocation.getTime() - mStoppedMovingAt) > mAutoPauseAfterSeconds * 1000) {
            mIsAutoPaused = true;
            setPaused(workout, true);
        } else if (!mHasStopped && !mIsAutoPaused) {
            mHasStopped = true;
            mStoppedMovingAt = lastLocation.getTime();
        }
    } else if (mIsAutoPaused && currentSpeed > mAutoPauseMinSpeed) {
        mIsAutoPaused = false;
        mHasStopped = false;
        setPaused(workout, false);
    }
}

36. PanicAlert#getLocation()

Project: PanicButton
File: PanicAlert.java
private Location getLocation(CurrentLocationProvider currentLocationProvider) {
    Location location = null;
    int retryCount = 0;
    while (retryCount < MAX_RETRIES && location == null) {
        location = currentLocationProvider.getLocation();
        if (location == null) {
            try {
                retryCount++;
                Thread.sleep(LOCATION_WAIT_TIME);
            } catch (InterruptedException e) {
                Log.e(TAG, "Location wait InterruptedException", e);
            }
        }
    }
    return location;
}

37. VehicleLocationProviderTest#testNotOverwrittenWhenDisabled()

Project: openxc-android
File: VehicleLocationProviderTest.java
@MediumTest
public void testNotOverwrittenWhenDisabled() {
    if (!mockLocationsEnabled(getContext())) {
        return;
    }
    prepareServices();
    locationProvider.setOverwritingStatus(false);
    source.inject(Latitude.ID, latitude + 1);
    source.inject(Longitude.ID, longitude);
    source.inject(VehicleSpeed.ID, speed);
    TestUtils.pause(100);
    Location lastAndroidLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (lastAndroidLocation != null) {
        assertTrue(lastAndroidLocation.getLatitude() != latitude + 1);
    }
}

38. LocationProvider#onConnected()

Project: open-location-code
File: LocationProvider.java
@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Connected to location services");
    LocationAvailability locationAvailability = mFusedLocationProviderApi.getLocationAvailability(mGoogleApiClient);
    if (!locationAvailability.isLocationAvailable()) {
        mLocationCallback.handleLocationNotAvailable();
        return;
    }
    Location lastKnownLocation = mFusedLocationProviderApi.getLastLocation(mGoogleApiClient);
    mFusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    if (lastKnownLocation != null) {
        Log.i(TAG, "Received last known location: " + lastKnownLocation);
        mCurrentBestLocation = lastKnownLocation;
        if (mBearing != null) {
            mCurrentBestLocation.setBearing(mBearing);
        }
        mLocationCallback.handleNewLocation(mCurrentBestLocation);
    }
}

39. CodePresenter#codeLocationUpdated()

Project: open-location-code
File: CodePresenter.java
@Override
public Direction codeLocationUpdated(double latitude, double longitude, boolean isCurrent) {
    OpenLocationCode code = OpenLocationCodeUtil.createOpenLocationCode(latitude, longitude);
    mView.displayCode(code);
    Location currentLocation = MainActivity.getMainPresenter().getCurrentLocation();
    Direction direction;
    if (isCurrent) {
        direction = new Direction(code, null, 0, 0);
    } else if (currentLocation == null) {
        direction = new Direction(null, code, 0, 0);
    } else {
        direction = DirectionUtil.getDirection(currentLocation, code);
    }
    return direction;
}

40. LocationHelper#getLastKnownLocation()

Project: MVPAndroidBootstrap
File: LocationHelper.java
public static Location getLastKnownLocation(Context context) {
    LocationManager mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}

41. LocationService#locationFix()

Project: MozStumbler
File: LocationService.java
private IResponse locationFix(Integer tile_id) {
    IResponse result = null;
    SmartTile coord = city_tiles.getCoord(tile_id);
    if (coord == null) {
        Log.w(LOG_TAG, "Couldn't find co-ordinates for tile_id=[" + tile_id + "]");
        return null;
    }
    Location roundTrip = coord.getLocation();
    JSONObject jsonLocation = LocationAdapter.toJSON(roundTrip);
    result = new HTTPResponse(200, new HashMap<String, List<String>>(), jsonLocation.toString().getBytes(), 0);
    Log.i(LOG_TAG, "Sending back location: " + jsonLocation.toString());
    return result;
}

42. LocationChangeSensorTest#testNotFirstGPSFix_MovedDistance()

Project: MozStumbler
File: LocationChangeSensorTest.java
@Test
public void testNotFirstGPSFix_MovedDistance() {
    Prefs.getInstance(ctx).setMotionChangeDistanceMeters(10000);
    locationChangeSensor.start();
    Location expectedPosition;
    // The second GPS fix must have movement > mPrefMotionChangeDistanceMeters
    // for the saved location to be updated.
    // If the second GPS fix is too soon, the accelerometers are registering movement
    // but the person hasn't actually moved geographically.  Keep the scanners on
    // and schedule the next timeout check to see if the user just stops moving around.
    expectedPosition = setPosition(20, 30);
    assertEquals(expectedPosition, locationChangeSensor.testing_getLastLocation());
    expectedPosition = setPosition(21, 30);
    // The new recorded position should be 21, 30
    assertEquals(expectedPosition, locationChangeSensor.testing_getLastLocation());
    setPosition(21.000001, 30);
    // The new recorded position should be unchanged, movement too small
    assertEquals(expectedPosition, locationChangeSensor.testing_getLastLocation());
}

43. MixMap#setStartPoint()

Project: mixare
File: MixMap.java
/* ********* Operators ***********/
public void setStartPoint() {
    Location location = getMixContext().getLocationFinder().getCurrentLocation();
    MapController controller;
    double latitude = location.getLatitude() * 1E6;
    double longitude = location.getLongitude() * 1E6;
    controller = getMapView().getController();
    startPoint = new GeoPoint((int) latitude, (int) longitude);
    controller.setCenter(startPoint);
    controller.setZoom(15);
}

44. LocationMgrImpl#locationCallback()

Project: mixare
File: LocationMgrImpl.java
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.mixare.mgr.location.LocationFinder#locationCallback(android.content
	 * .Context)
	 */
public void locationCallback(String provider) {
    Location foundLocation = lm.getLastKnownLocation(provider);
    if (bestLocationProvider != null) {
        Location bestLocation = lm.getLastKnownLocation(bestLocationProvider);
        if (foundLocation.getAccuracy() < bestLocation.getAccuracy()) {
            curLoc = foundLocation;
            bestLocationProvider = provider;
        }
    } else {
        curLoc = foundLocation;
        bestLocationProvider = provider;
    }
    setLocationAtLastDownload(curLoc);
}

45. DeviceLocation#getLastKnownLocation()

Project: kickflip-android-sdk
File: DeviceLocation.java
/**
     * Get the last known location.
     * If one is not available, fetch
     * a fresh location
     *
     * @param context
     * @param waitForGpsFix
     * @param cb
     */
public static void getLastKnownLocation(Context context, boolean waitForGpsFix, final LocationResult cb) {
    DeviceLocation deviceLocation = new DeviceLocation();
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location last_loc;
    last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (last_loc == null)
        last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (last_loc != null && cb != null) {
        cb.gotLocation(last_loc);
    } else {
        deviceLocation.getLocation(context, cb, waitForGpsFix);
    }
}

46. UtilityService#locationUpdated()

Project: io2015-codelabs
File: UtilityService.java
/**
     * Called when the location has been updated
     */
private void locationUpdated(Intent intent) {
    Log.v(TAG, ACTION_LOCATION_UPDATED);
    // Extra new location
    Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
    if (location != null) {
        LatLng latLngLocation = new LatLng(location.getLatitude(), location.getLongitude());
        // Store in a local preference as well
        Utils.storeLocation(this, latLngLocation);
        // Send a local broadcast so if an Activity is open it can respond
        // to the updated location
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}

47. UtilityService#locationUpdated()

Project: io2015-codelabs
File: UtilityService.java
/**
     * Called when the location has been updated
     */
private void locationUpdated(Intent intent) {
    Log.v(TAG, ACTION_LOCATION_UPDATED);
    // Extra new location
    Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
    if (location != null) {
        LatLng latLngLocation = new LatLng(location.getLatitude(), location.getLongitude());
        // Store in a local preference as well
        Utils.storeLocation(this, latLngLocation);
        // Send a local broadcast so if an Activity is open it can respond
        // to the updated location
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}

48. MainActivity#getCoordinates()

Project: Grant
File: MainActivity.java
private double[] getCoordinates() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);
    Location l = null;
    for (int i = providers.size() - 1; i >= 0; i--) {
        //noinspection ResourceType
        l = lm.getLastKnownLocation(providers.get(i));
        if (l != null)
            break;
    }
    double[] gps = new double[2];
    if (l != null) {
        gps[0] = l.getLatitude();
        gps[1] = l.getLongitude();
    }
    return gps;
}

49. Kml22AnnotateHandlerTest#GetPlacemarkXml_BasicLocation_BasicPlacemarkNodeReturned()

Project: gpslogger
File: Kml22AnnotateHandlerTest.java
@Test
public void GetPlacemarkXml_BasicLocation_BasicPlacemarkNodeReturned() {
    Kml22AnnotateHandler kmlHandler = new Kml22AnnotateHandler(null, null, null);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).build();
    String actual = kmlHandler.getPlacemarkXml("This is the annotation", loc);
    String expected = "<Placemark><name>This is the annotation</name><Point><coordinates>19.111,12.193,9001.0</coordinates></Point></Placemark>\n";
    assertThat("Basic Placemark XML", actual, is(expected));
}

50. Gpx10WriteHandlerTest#GetTrackPointXml_BundledGeoIdHeight_GeoIdHeightNode()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackPointXml_BundledGeoIdHeight_GeoIdHeightNode() {
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, true);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).putExtra("GEOIDHEIGHT", "MYGEOIDHEIGHT").build();
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkseg><trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time><course>91.88</course><speed>188.44</speed><geoidheight>MYGEOIDHEIGHT</geoidheight><src>MOCK</src></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Trackpoint XML with a geoid height", actual, is(expected));
}

51. Gpx10WriteHandlerTest#GetTrackPointXml_WhenHDOPPresent_ThenFormattedInXML()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackPointXml_WhenHDOPPresent_ThenFormattedInXML() {
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, true);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).putExtra("HDOP", "LOOKATTHISHDOP!").build();
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkseg><trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>" + "<course>91.88</course><speed>188.44</speed><src>MOCK</src><hdop>LOOKATTHISHDOP!</hdop></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Trackpoint XML with an HDOP", actual, is(expected));
}

52. Gpx10WriteHandlerTest#GetTrackPointXml_NewTrackSegmentPref_NewTrkSegReturned()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackPointXml_NewTrackSegmentPref_NewTrkSegReturned() {
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, true);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).build();
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkseg><trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>" + "<course>91.88</course><speed>188.44</speed><src>MOCK</src></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Trackpoint XML with a new segment", actual, is(expected));
}

53. Gpx10WriteHandlerTest#GetTrackpointXml_DefaultSatellitesNotPresent_TrkptNodeUsesSelfTrackedSatellites()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackpointXml_DefaultSatellitesNotPresent_TrkptNodeUsesSelfTrackedSatellites() {
    //loc.getExtras().getInt("satellites",-1) should contain the provider specified satellites used in fix
    //If that isn't present, use the one we passed in as our own extra - SATELLITES_FIX
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).withAccuracy(55f).putExtra("SATELLITES_FIX", 22).build();
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, false);
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>" + "<course>91.88</course><speed>188.44</speed><src>MOCK</src><sat>22</sat></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Trackpoint uses satellites used in fix", actual, is(expected));
}

54. Gpx10WriteHandlerTest#GetTrackpointXml_NumberOfSatellites_TrkptNodeUsesSatellitesUsedInFix()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackpointXml_NumberOfSatellites_TrkptNodeUsesSatellitesUsedInFix() {
    //loc.getExtras().getInt("satellites",-1) should contain the provider specified satellites used in fix
    //If that isn't present, use the one we passed in as our own extra - SATELLITES_FIX
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).withAccuracy(55f).putExtra("satellites", 9).putExtra("SATELLITES_FIX", 22).build();
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, false);
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>" + "<course>91.88</course><speed>188.44</speed><src>MOCK</src><sat>9</sat></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Trackpoint uses satellites used in fix", actual, is(expected));
}

55. Gpx10WriteHandlerTest#GetTrackPointXml_LocationWithoutSatellites_TrkptNodeReturned()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackPointXml_LocationWithoutSatellites_TrkptNodeReturned() {
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, false);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).withAccuracy(55f).build();
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>" + "<course>91.88</course><speed>188.44</speed><src>MOCK</src></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Trackpoint XML without satellites", actual, is(expected));
}

56. Gpx10WriteHandlerTest#GetTrackPointXml_LocationWithAltBearingSpeed_TrkptWithEleCourseSpeedReturned()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackPointXml_LocationWithAltBearingSpeed_TrkptWithEleCourseSpeedReturned() {
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, false);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).build();
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>" + "<course>91.88</course><speed>188.44</speed><src>MOCK</src></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Trackpoint XML with all info", actual, is(expected));
}

57. Gpx10WriteHandlerTest#GetTrackpointXml_BasicLocation_BasicTrkptNodeReturned()

Project: gpslogger
File: Gpx10WriteHandlerTest.java
@Test
public void GetTrackpointXml_BasicLocation_BasicTrkptNodeReturned() {
    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, false);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).build();
    String actual = writeHandler.getTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected = "<trkpt lat=\"12.193\" lon=\"19.111\"><time>2011-09-17T18:45:33Z</time><src>MOCK</src></trkpt>\n</trkseg></trk></gpx>";
    assertThat("Basic trackpoint XML", actual, is(expected));
}

58. Gpx10AnnotateHandlerTest#GetWaypointXml_BasicLocation_BasicWptNodeReturned()

Project: gpslogger
File: Gpx10AnnotateHandlerTest.java
@Test
public void GetWaypointXml_BasicLocation_BasicWptNodeReturned() {
    Gpx10AnnotateHandler annotateHandler = new Gpx10AnnotateHandler(null, null, null, null);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).build();
    when(loc.hasAccuracy()).thenReturn(false);
    String actual = annotateHandler.getWaypointXml(loc, "2011-09-17T18:45:33Z", "This is the annotation");
    String expected = "\n<wpt lat=\"12.193\" lon=\"19.111\"><time>2011-09-17T18:45:33Z</time><name>This is the annotation</name><src>MOCK</src></wpt>\n";
    assertThat("Basic waypoint XML", actual, is(expected));
}

59. CustomUrlLoggerTest#getFormattedUrl_WhenValuesMissing_UrlReturnsWhatsAvailable()

Project: gpslogger
File: CustomUrlLoggerTest.java
@Test
public void getFormattedUrl_WhenValuesMissing_UrlReturnsWhatsAvailable() throws Exception {
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withTime(1457205869949l).build();
    CustomUrlLogger logger = new CustomUrlLogger("", 0, "");
    String expected = "http://192.168.1.65:8000/test?lat=12.193&lon=19.111&sat=0&desc=&alt=0.0&acc=0.0&dir=0.0&prov=MOCK&spd=0.0&time=2016-03-05T19:24:29Z&battery=0.0&androidId=&serial=";
    String urlTemplate = "http://192.168.1.65:8000/test?lat=%LAT&lon=%LON&sat=%SAT&desc=%DESC&alt=%ALT&acc=%ACC&dir=%DIR&prov=%PROV&spd=%SPD&time=%TIME&battery=%BATT&androidId=%AID&serial=%SER";
    assertThat("Placeholders are substituted", logger.getFormattedUrl(urlTemplate, loc, "", "", 0, ""), is(expected));
}

60. CustomUrlLoggerTest#getFormattedUrl_WhenPlaceholders_ValuesSubstituted()

Project: gpslogger
File: CustomUrlLoggerTest.java
@Test
public void getFormattedUrl_WhenPlaceholders_ValuesSubstituted() throws Exception {
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).putExtra("satellites", 9).withAltitude(45).withAccuracy(8).withBearing(359).withSpeed(9001).withTime(1457205869949l).build();
    CustomUrlLogger logger = new CustomUrlLogger("", 0, "");
    String expected = "http://192.168.1.65:8000/test?lat=12.193&lon=19.111&sat=9&desc=blah&alt=45.0&acc=8.0&dir=359.0&prov=MOCK&spd=9001.0&time=2016-03-05T19:24:29Z&battery=91.0&androidId=22&serial=SRS11";
    String urlTemplate = "http://192.168.1.65:8000/test?lat=%LAT&lon=%LON&sat=%SAT&desc=%DESC&alt=%ALT&acc=%ACC&dir=%DIR&prov=%PROV&spd=%SPD&time=%TIME&battery=%BATT&androidId=%AID&serial=%SER";
    assertThat("Placeholders are substituted", logger.getFormattedUrl(urlTemplate, loc, "blah", "22", 91, "SRS11"), is(expected));
}

61. PlainTextFileLoggerTest#getCsvLine_LocationWithSatellites_ReturnsCSVLine()

Project: gpslogger
File: PlainTextFileLoggerTest.java
@Test
public void getCsvLine_LocationWithSatellites_ReturnsCSVLine() {
    PlainTextFileLogger plain = new PlainTextFileLogger(null);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(101).withAccuracy(41).withBearing(119).withSpeed(9).putExtra("satellites", 7).putExtra("SATELLITES_FIX", 22).build();
    String actual = plain.getCsvLine(loc, "2011-09-17T18:45:33Z");
    String expected = "2011-09-17T18:45:33Z,12.193000,19.111000,101.0,41.0,119.0,9.0,7,MOCK,,,,,,\n";
    assertThat("CSV line with satellites or SATELLITES_FIX", actual, is(expected));
}

62. SimpleLocationManager#getCurrentLocation()

Project: droidar
File: SimpleLocationManager.java
/**
	 * @param accuracy
	 *            see the {@link Criteria#setAccuracy(int)} method for possible
	 *            parameter types
	 * @return
	 */
public Location getCurrentLocation(int accuracy) {
    Location l = getCurrentBUfferedLocation();
    if (l != null) {
        return l;
    }
    if (context != null) {
        try {
            LocationManager lm = getLocationManager();
            Criteria criteria = new Criteria();
            criteria.setAccuracy(accuracy);
            return lm.getLastKnownLocation(lm.getBestProvider(criteria, true));
        } catch (Exception e) {
            Log.e(LOG_TAG, "Could not receive the current location");
            e.printStackTrace();
            return null;
        }
    }
    Log.e(LOG_TAG, "The passed activity was null!");
    return null;
}

63. EventManager#getCurrentLocationObject()

Project: droidar
File: EventManager.java
/**
	 * This will return the current position of the device according to the
	 * Android system values.
	 * 
	 * The resulting coordinates can differ from
	 * {@link GLCamera#getGPSLocation()} if the camera was not moved according
	 * to the GPS input (eg moved via trackball).
	 * 
	 * Also check the {@link EventManager#getZeroPositionLocationObject()}
	 * method, if you want to know where the virtual zero position (of the
	 * OpenGL world) is.
	 */
public GeoObj getCurrentLocationObject() {
    Location locaction = getCurrentLocation();
    if (locaction != null) {
        if (currentLocation == null) {
            currentLocation = new GeoObj(locaction, false);
        } else {
            currentLocation.setLocation(locaction);
        }
        return currentLocation;
    } else {
        Log.e(LOG_TAG, "Couldn't receive Location object for current location");
    }
    // if its still null set it to a default geo-object:
    if (currentLocation == null) {
        Log.e(LOG_TAG, "Current position set to default 0,0 position");
        currentLocation = new GeoObj(false);
    }
    return currentLocation;
}

64. ShowLocationActivity#onCreate()

Project: codeexamples-android
File: ShowLocationActivity.java
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    latituteField = (TextView) findViewById(R.id.TextView02);
    longitudeField = (TextView) findViewById(R.id.TextView04);
    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    // Initialize the location fields
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
    } else {
        latituteField.setText("Location not available");
        longitudeField.setText("Location not available");
    }
}

65. GeoTypeAdapter#read()

Project: apps-android-wikipedia
File: GeoTypeAdapter.java
@Override
public Location read(JsonReader in) throws IOException {
    Location ret = new Location((String) null);
    in.beginObject();
    while (in.hasNext()) {
        String name = in.nextName();
        switch(name) {
            case GeoUnmarshaller.LATITUDE:
                ret.setLatitude(in.nextDouble());
                break;
            case GeoUnmarshaller.LONGITUDE:
                ret.setLongitude(in.nextDouble());
                break;
            default:
                L.d("name=" + name);
                break;
        }
    }
    in.endObject();
    return ret;
}

66. NearbyFragment#goToUserLocation()

Project: apps-android-wikipedia
File: NearbyFragment.java
private void goToUserLocation() {
    if (mapboxMap == null) {
        return;
    }
    Location location = mapboxMap.getMyLocation();
    if (location != null) {
        CameraPosition pos = new CameraPosition.Builder().target(new LatLng(location)).zoom(getResources().getInteger(R.integer.map_default_zoom)).build();
        mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(pos));
    }
    fetchNearbyPages();
}

67. BackendHelper#update()

Project: android_packages_apps_UnifiedNlp
File: BackendHelper.java
/**
     * Requests a location update from the backend.
     *
     * @return The location reported by the backend. This may be null if a backend cannot determine its
     * location, or if it is going to return a location asynchronously.
     */
public Location update() {
    Location result = null;
    if (backend == null) {
        Log.d(TAG, "Not (yet) bound.");
        updateWaiting = true;
    } else {
        updateWaiting = false;
        try {
            result = backend.update();
            if (result != null && (lastLocation == null || result.getTime() > lastLocation.getTime())) {
                setLastLocation(result);
                backendFuser.reportLocation();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
            unbind();
        }
    }
    return result;
}

68. BackendFuser#updateLocation()

Project: android_packages_apps_UnifiedNlp
File: BackendFuser.java
void updateLocation() {
    List<Location> locations = new ArrayList<Location>();
    for (BackendHelper handler : backendHelpers) {
        locations.add(handler.getLastLocation());
    }
    Location location = mergeLocations(locations);
    if (location != null) {
        location.setProvider(LocationManager.NETWORK_PROVIDER);
        if (lastLocationReportTime < location.getTime()) {
            lastLocationReportTime = location.getTime();
            locationProvider.reportLocation(location);
            Log.v(TAG, "location=" + location);
        } else {
            Log.v(TAG, "Ignoring location update as it's older than other provider.");
        }
    }
}

69. MainActivity#startGeofence()

Project: AndroidDemoProjects
File: MainActivity.java
private void startGeofence() {
    Location location = mLocationClient.getLastLocation();
    Geofence.Builder builder = new Geofence.Builder();
    mGeofence = builder.setRequestId(FENCE_ID).setCircularRegion(location.getLatitude(), location.getLongitude(), RADIUS).setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT).setExpirationDuration(Geofence.NEVER_EXPIRE).build();
    ArrayList<Geofence> geofences = new ArrayList<Geofence>();
    geofences.add(mGeofence);
    mLocationClient.addGeofences(geofences, mPendingIntent, this);
}

70. MainActivityTest#testUsingMockLocation()

Project: android-play-location
File: MainActivityTest.java
/**
     * Tests location using a mock location object.
     */
public void testUsingMockLocation() {
    Log.v(TAG, "Testing current location");
    // Use a Location object set to the coordinates of the North Pole to set the mock location.
    setMockLocation(createNorthPoleLocation());
    // Make sure that the activity under test exists and GoogleApiClient is connected.
    confirmPreconditions();
    // Simulate a Start Updates button click.
    clickStartUpdatesButton();
    final Location testLocation = createNorthPoleLocation();
    assertEquals(testLocation.getLatitude(), mMainActivity.mCurrentLocation.getLatitude(), 0.000001f);
    assertEquals(testLocation.getLongitude(), mMainActivity.mCurrentLocation.getLongitude(), 0.000001f);
    assertEquals(String.valueOf(testLocation.getLatitude()), mMainActivity.mLatitudeTextView.getText().toString());
    assertEquals(String.valueOf(testLocation.getLongitude()), mMainActivity.mLongitudeTextView.getText().toString());
}

71. Utils#getExifLocation()

Project: android-open-project-demo
File: Utils.java
public static Location getExifLocation(String filepath) {
    Location location = null;
    try {
        final ExifInterface exif = new ExifInterface(filepath);
        final float[] latLong = new float[2];
        if (exif.getLatLong(latLong)) {
            location = new Location("");
            location.setLatitude(latLong[0]);
            location.setLongitude(latLong[1]);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return location;
}

72. MockLocationProvider#pushLocation()

Project: coursera-android-labs
File: MockLocationProvider.java
public void pushLocation(double lat, double lon) {
    Location mockLocation = new Location(mProviderName);
    mockLocation.setLatitude(lat);
    mockLocation.setLongitude(lon);
    mockLocation.setAltitude(0);
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    mockLocation.setAccuracy(sMockAccuracy);
    mLocationManager.setTestProviderLocation(mProviderName, mockLocation);
}

73. StumblerBundleTest#testToGeolocateJSON()

Project: MozStumbler
File: StumblerBundleTest.java
@Test
public void testToGeolocateJSON() throws JSONException {
    JSONObject expectedJson = getExpectedGeoLocate();
    // a string
    Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
    mockLocation.setLatitude(-22.5f);
    mockLocation.setLongitude(-43.5f);
    mockLocation.setTime(1405602028568L);
    mockLocation.setAccuracy(20.5f);
    mockLocation.setAltitude(202.9f);
    assertTrue(mockLocation.hasAccuracy());
    assertTrue(mockLocation.hasAltitude());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    StumblerBundle bundle = new StumblerBundle(mockLocation);
    for (String bssid : new String[] { "01:23:45:67:89:ab", "23:45:67:89:ab:cd" }) {
        ScanResult scanResult = createScanResult(bssid, "", 0, 0, 0);
        bundle.addWifiData(bssid, scanResult);
    }
    CellInfo cellInfo = createLteCellInfo(208, 1, 12345, CellInfo.UNKNOWN_CID, 2, 31, 1);
    bundle.addCellData(cellInfo.getCellIdentity(), cellInfo);
    JSONObject actualJson = bundle.toMLSGeolocate();
    JSONAssert.assertEquals(expectedJson, actualJson, true);
}

74. StumblerBundleTest#testToGeosubmitJSON()

Project: MozStumbler
File: StumblerBundleTest.java
@Test
public void testToGeosubmitJSON() throws JSONException {
    ISystemClock clock = (ISystemClock) ServiceLocator.getInstance().getService(ISystemClock.class);
    JSONObject expectedJson = getExpectedGeosubmit();
    // a string
    Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
    mockLocation.setLatitude(-22.5f);
    mockLocation.setLongitude(-43.5f);
    mockLocation.setTime(clock.currentTimeMillis());
    mockLocation.setAccuracy(20.5f);
    mockLocation.setAltitude(202.9f);
    assertTrue(mockLocation.hasAccuracy());
    assertTrue(mockLocation.hasAltitude());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    StumblerBundle bundle = new StumblerBundle(mockLocation);
    for (String bssid : new String[] { "01:23:45:67:89:ab", "23:45:67:89:ab:cd" }) {
        ScanResult scanResult = createScanResult(bssid, "", 0, 0, 0);
        bundle.addWifiData(bssid, scanResult);
    }
    CellInfo cellInfo = createLteCellInfo(208, 1, 12345, CellInfo.UNKNOWN_CID, 2, 31, 1);
    bundle.addCellData(cellInfo.getCellIdentity(), cellInfo);
    List<StumblerBundle> bundleList = new ArrayList<StumblerBundle>();
    bundleList.add(bundle);
    ReportBatchBuilder rbb = new ReportBatchBuilder();
    for (StumblerBundle b : bundleList) {
        rbb.addRow(b.toMLSGeosubmit());
    }
    String finalReport = Zipper.unzipData(rbb.finalizeToJSONRowsObject().data);
    JSONObject actualJson = new JSONObject(finalReport);
    JSONAssert.assertEquals(expectedJson, actualJson, true);
}

75. LocationTestUtil#location()

Project: PanicButton
File: LocationTestUtil.java
public static Location location(String provider, double latitude, double longitude, long time, float accuracy) {
    Location location = new Location(provider);
    location.setLatitude(latitude);
    location.setLongitude(longitude);
    location.setTime(time);
    location.setAccuracy(accuracy);
    return location;
}

76. LocationService#adjust_center_with_adjacent_wifi()

Project: MozStumbler
File: LocationService.java
private Location adjust_center_with_adjacent_wifi(int center_tile_id, int center_height, int[] tile_points) {
    SmartTile coord = city_tiles.getCoord(center_tile_id);
    Location loc = coord.getLocation();
    double c_lat = loc.getLatitude();
    double c_lon = loc.getLongitude();
    Log.i(LOG_TAG, "Center is at : " + c_lat + ", " + c_lon);
    List<HashMap<String, Double>> weighted_lat_lon = new ArrayList<HashMap<String, Double>>();
    for (int adj_tileid : adjacent_tile(center_tile_id)) {
        SmartTile adj_coord = city_tiles.getCoord(adj_tileid);
        int adj_pts = tile_points[adj_tileid];
        if (adj_pts > 0) {
            Location adj_loc = adj_coord.getLocation();
            Log.i(LOG_TAG, "Extra points at: " + adj_tileid + ", " + adj_pts);
            Log.i(LOG_TAG, "Lat Lon for " + adj_tileid + " is " + adj_loc.getLatitude() + ", " + adj_loc.getLongitude());
            HashMap<String, Double> v = new HashMap<String, Double>();
            v.put(ADJ_PTS, (double) adj_pts);
            v.put(LAT, adj_loc.getLatitude());
            v.put(LON, adj_loc.getLongitude());
            weighted_lat_lon.add(v);
        }
    }
    double w_lat = 0;
    double w_lon = 0;
    double total_shift_weight = 0;
    for (HashMap<String, Double> v : weighted_lat_lon) {
        w_lat += v.get(LAT) * v.get(ADJ_PTS);
        w_lon += v.get(LON) * v.get(ADJ_PTS);
        total_shift_weight += v.get(ADJ_PTS);
    }
    w_lat /= total_shift_weight;
    w_lon /= total_shift_weight;
    Log.i(LOG_TAG, "Adjacent w_lat, w_lon : " + w_lat + ", " + w_lon);
    double n_lat = c_lat * 0.5 + w_lat * 0.5;
    double n_lon = c_lon * 0.5 + w_lat * 0.5;
    // There's only GPS, NETWORK and PASSIVE providers specified in
    // LocationManager.
    Location result = new Location(LocationManager.NETWORK_PROVIDER);
    result.setLatitude(n_lat);
    result.setLongitude(n_lon);
    result.setAccuracy(150);
    Log.i(LOG_TAG, "Recomputed lat/lon: [" + result.getLatitude() + "], [" + result.getLongitude() + "]");
    return result;
}

77. MainActivityTest#createNorthPoleLocation()

Project: android-play-location
File: MainActivityTest.java
/**
     * Creates and returns a Location object set to the coordinates of the North Pole.
     */
private Location createNorthPoleLocation() {
    Location mockLocation = new Location(NORTH_POLE);
    mockLocation.setLatitude(NORTH_POLE_LATITUDE);
    mockLocation.setLongitude(NORTH_POLE_LONGITUDE);
    mockLocation.setAccuracy(ACCURACY_IN_METERS);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    mockLocation.setTime(System.currentTimeMillis());
    return mockLocation;
}

78. LocationUtilsTest#testGetLocation()

Project: socialize-sdk-android
File: LocationUtilsTest.java
public void testGetLocation() {
    final Location mockLocation = new Location((String) null);
    mockLocation.setLatitude(69);
    mockLocation.setLongitude(96);
    // Stub in location provider and manager
    SocializeLocationManager mockLocationManager = new SocializeLocationManager(null) {

        @Override
        public void init(Context context) {
        }

        @Override
        public String getBestProvider(Criteria criteria, boolean enabledOnly) {
            return "foobar";
        }

        @Override
        public Location getLastKnownLocation(String provider) {
            return mockLocation;
        }

        @Override
        public boolean isProviderEnabled(String provider) {
            return true;
        }

        @Override
        public void requestLocationUpdates(Activity activity, String provider, long minTime, float minDistance, LocationListener listener) {
        }

        @Override
        public void removeUpdates(LocationListener listener) {
        }
    };
    SocializeLocationProvider mockLocationProvider = new DefaultLocationProvider() {

        @Override
        public Location getLastKnownLocation() {
            return mockLocation;
        }

        @Override
        public Location getLocation(Context context) {
            return mockLocation;
        }
    };
    SocializeIOC.registerStub("locationManager", mockLocationManager);
    SocializeIOC.registerStub("locationProvider", mockLocationProvider);
    Location location = LocationUtils.getLastKnownLocation(getContext());
    SocializeIOC.unregisterStub("locationManager");
    SocializeIOC.unregisterStub("locationProvider");
    assertNotNull(location);
    assertEquals(mockLocation.getLongitude(), location.getLongitude());
    assertEquals(mockLocation.getLatitude(), location.getLatitude());
}

79. LocationAdapter#fromJSON()

Project: MozStumbler
File: LocationAdapter.java
public static Location fromJSON(JSONObject jsonObj) {
    Location location = new Location(AppGlobals.LOCATION_ORIGIN_INTERNAL);
    location.setLatitude(getLat(jsonObj));
    location.setLongitude(getLng(jsonObj));
    location.setAccuracy(getAccuracy(jsonObj));
    return location;
}

80. SmartTile#getLocation()

Project: MozStumbler
File: SmartTile.java
public Location getLocation() {
    Location location = new Location(LocationManager.NETWORK_PROVIDER);
    location.setAccuracy(150);
    location.setLatitude(tile2lat());
    location.setLongitude(tile2lon());
    return location;
}

81. LocationActivityTest#location()

Project: MozStumbler
File: LocationActivityTest.java
private Location location(String provider, double latitude, double longitude) {
    Location location = new Location(provider);
    location.setLatitude(latitude);
    location.setLongitude(longitude);
    location.setTime(System.currentTimeMillis());
    return location;
}

82. AbstractIgnitedLocationManagerTest#getMockLocation()

Project: ignition
File: AbstractIgnitedLocationManagerTest.java
protected Location getMockLocation(double lat, double lon) {
    Location location = new Location(LocationManager.GPS_PROVIDER);
    location.setLatitude(lat);
    location.setLongitude(lon);
    location.setAccuracy(DEFAULT_ACCURACY);
    return location;
}

83. GLCamera#getGPSLocation()

Project: droidar
File: GLCamera.java
/**
	 * @return The position where the camera moves to. Will be NULL if new
	 *         position never set before!
	 */
// public Vec getMyNewPosition() {
//
// return myNewPosition;
// }
/**
	 * The resulting coordinates can differ from
	 * {@link EventManager#getCurrentLocationObject()} if the camera was not
	 * moved according to the GPS input (eg moved via trackball).
	 * 
	 * @return
	 */
public Location getGPSLocation() {
    Vec coords = getGPSPositionVec();
    Location pos = new Location("customCreated");
    pos.setLatitude(coords.y);
    pos.setLongitude(coords.x);
    pos.setAltitude(coords.z);
    return pos;
}

84. GeoObj#toLocation()

Project: droidar
File: GeoObj.java
public Location toLocation() {
    Location x = new Location("customCreated");
    x.setLatitude(getLatitude());
    x.setLongitude(getLongitude());
    x.setAltitude(getAltitude());
    return x;
}

85. LocationDeserializer#deserialize()

Project: YourAppIdea
File: LocationDeserializer.java
@Override
public Location deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    Location location = new Location("mongodb");
    JsonArray coord = jsonObject.getAsJsonArray("coordinates");
    location.setLongitude(coord.get(0).getAsDouble());
    location.setLatitude(coord.get(1).getAsDouble());
    return location;
}

86. ExploreFragment#getMapCenterLocation()

Project: rox-android
File: ExploreFragment.java
private Location getMapCenterLocation() {
    Location location = new Location(LocationManager.GPS_PROVIDER);
    location.setLatitude(googleMap.getCameraPosition().target.latitude);
    location.setLongitude(googleMap.getCameraPosition().target.longitude);
    return location;
}

87. LocationProvider#connectUsingOldApi()

Project: open-location-code
File: LocationProvider.java
private void connectUsingOldApi() {
    Location lastKnownGpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Location lastKnownNetworkLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    Location bestLastKnownLocation = mCurrentBestLocation;
    if (lastKnownGpsLocation != null && LocationUtil.isBetterLocation(lastKnownGpsLocation, bestLastKnownLocation)) {
        bestLastKnownLocation = lastKnownGpsLocation;
    }
    if (lastKnownNetworkLocation != null && LocationUtil.isBetterLocation(lastKnownNetworkLocation, bestLastKnownLocation)) {
        bestLastKnownLocation = lastKnownNetworkLocation;
    }
    mCurrentBestLocation = bestLastKnownLocation;
    if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER) && mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, mGpsLocationListener);
    }
    if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER) && mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, mNetworkLocationListener);
    }
    if (bestLastKnownLocation != null) {
        Log.i(TAG, "Received last known location via old API: " + bestLastKnownLocation);
        if (mBearing != null) {
            bestLastKnownLocation.setBearing(mBearing);
        }
        mLocationCallback.handleNewLocation(bestLastKnownLocation);
    }
}

88. TypeConverterTest#testConverters()

Project: DBFlow
File: TypeConverterTest.java
@Test
public void testConverters() {
    Delete.table(TestType.class);
    TestType testType = new TestType();
    testType.setName("Name");
    long testTime = System.currentTimeMillis();
    // calendar
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(testTime);
    testType.calendar = calendar;
    Date date = new Date(testTime);
    testType.date = date;
    java.sql.Date date1 = new java.sql.Date(testTime);
    testType.sqlDate = date1;
    JSONObject jsonObject;
    try {
        jsonObject = new JSONObject("{ name: test, happy: true }");
        testType.json = jsonObject;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    Location location = new Location("test");
    location.setLatitude(40.5);
    location.setLongitude(40.5);
    testType.location = location;
    testType.save();
    TestType retrieved = new Select().from(TestType.class).where(TestType_Table.name.is("Name")).querySingle();
    assertNotNull(retrieved);
    assertNotNull(retrieved.calendar);
    assertTrue(retrieved.calendar.equals(calendar));
    assertNotNull(retrieved.date);
    assertTrue(retrieved.date.equals(date));
    assertNotNull(retrieved.sqlDate);
    assertTrue(retrieved.sqlDate.equals(date1));
    assertNotNull(retrieved.json);
    assertTrue(retrieved.json.toString().equals(jsonObject.toString()));
    assertNotNull(retrieved.location);
    assertTrue(retrieved.location.getLongitude() == location.getLongitude());
    assertTrue(retrieved.location.getLatitude() == location.getLatitude());
}

89. LocationConverter#getModelValue()

Project: DBFlow
File: LocationConverter.java
@Override
public Location getModelValue(String data) {
    if (data == null) {
        return null;
    }
    String[] values = data.split(",");
    Location location = new Location("");
    location.setLatitude(Double.valueOf(values[0]));
    location.setLongitude(Double.valueOf(values[1]));
    return location;
}

90. NewMap#getCoordinates()

Project: cgeo
File: NewMap.java
public Location getCoordinates() {
    final LatLong center = mapView.getModel().mapViewPosition.getCenter();
    final Location loc = new Location("newmap");
    loc.setLatitude(center.latitude);
    loc.setLongitude(center.longitude);
    return loc;
}

91. PlacePickerFragmentTests#testCanSetParametersProgrammatically()

Project: astrid
File: PlacePickerFragmentTests.java
@MediumTest
@LargeTest
public void testCanSetParametersProgrammatically() throws Throwable {
    TestActivity activity = getActivity();
    assertNotNull(activity);
    final Location location = new Location("");
    location.setLatitude(47.6204);
    location.setLongitude(-122.3491);
    runAndBlockOnUiThread(0, new Runnable() {

        @Override
        public void run() {
            Bundle bundle = new Bundle();
            // We deliberately set these to non-defaults to ensure they are set correctly.
            bundle.putBoolean(PlacePickerFragment.SHOW_PICTURES_BUNDLE_KEY, false);
            bundle.putInt(PlacePickerFragment.RADIUS_IN_METERS_BUNDLE_KEY, 75);
            bundle.putInt(PlacePickerFragment.RESULTS_LIMIT_BUNDLE_KEY, 5);
            bundle.putString(PlacePickerFragment.SEARCH_TEXT_BUNDLE_KEY, "coffee");
            bundle.putParcelable(PlacePickerFragment.LOCATION_BUNDLE_KEY, location);
            bundle.putString(FriendPickerFragment.EXTRA_FIELDS_BUNDLE_KEY, "checkins,general_info");
            PlacePickerFragment fragment = new PlacePickerFragment(bundle);
            getActivity().setContentToFragment(fragment);
        }
    });
    // We don't just test the fragment we created directly above, because we want it to go through the
    // activity lifecycle and ensure the settings are still correct.
    final PlacePickerFragment fragment = activity.getFragment();
    assertNotNull(fragment);
    assertEquals(false, fragment.getShowPictures());
    assertEquals(75, fragment.getRadiusInMeters());
    assertEquals(5, fragment.getResultsLimit());
    assertEquals("coffee", fragment.getSearchText());
    assertEquals(location, fragment.getLocation());
    Collection<String> extraFields = fragment.getExtraFields();
    assertTrue(extraFields.contains("checkins"));
    assertTrue(extraFields.contains("general_info"));
}

92. GraphObjectPagingLoaderTests#testLoaderFinishesImmediatelyOnNoResults()

Project: astrid
File: GraphObjectPagingLoaderTests.java
@MediumTest
@LargeTest
public void testLoaderFinishesImmediatelyOnNoResults() throws Exception {
    CountingCallback callback = new CountingCallback();
    final GraphObjectPagingLoader<GraphPlace> loader = (GraphObjectPagingLoader<GraphPlace>) getActivity().getSupportLoaderManager().initLoader(0, null, callback);
    TestSession session = openTestSessionWithSharedUser();
    // Unlikely to ever be a Place here.
    Location location = new Location("");
    location.setLatitude(-1.0);
    location.setLongitude(-1.0);
    final Request request = Request.newPlacesSearchRequest(session, location, 10, 5, null, null);
    // Need to run this on blocker thread so callbacks are made there.
    runOnBlockerThread(new Runnable() {

        @Override
        public void run() {
            loader.startLoading(request, false);
        }
    }, false);
    getTestBlocker().waitForSignals(1);
    assertEquals(1, callback.onLoadFinishedCount);
    assertEquals(0, callback.onErrorCount);
    assertEquals(0, callback.onLoadResetCount);
    assertNotNull(callback.results);
    assertEquals(0, callback.results.getCount());
}

93. GraphObjectPagingLoaderTests#testLoaderLoadsAndFollowsNextLinks()

Project: astrid
File: GraphObjectPagingLoaderTests.java
@MediumTest
@LargeTest
public void testLoaderLoadsAndFollowsNextLinks() throws Exception {
    CountingCallback callback = new CountingCallback();
    final GraphObjectPagingLoader<GraphPlace> loader = (GraphObjectPagingLoader<GraphPlace>) getActivity().getSupportLoaderManager().initLoader(0, null, callback);
    TestSession session = openTestSessionWithSharedUser();
    Location location = new Location("");
    location.setLatitude(47.6204);
    location.setLongitude(-122.3491);
    final Request request = Request.newPlacesSearchRequest(session, location, 1000, 5, null, null);
    // Need to run this on blocker thread so callbacks are made there.
    runOnBlockerThread(new Runnable() {

        @Override
        public void run() {
            loader.startLoading(request, false);
        }
    }, false);
    getTestBlocker().waitForSignals(1);
    assertEquals(1, callback.onLoadFinishedCount);
    assertEquals(0, callback.onErrorCount);
    assertEquals(0, callback.onLoadResetCount);
    // We might not get back the exact number we requested because of privacy or other rules on
    // the service side.
    assertNotNull(callback.results);
    assertTrue(callback.results.getCount() > 0);
    runOnBlockerThread(new Runnable() {

        @Override
        public void run() {
            loader.followNextLink();
        }
    }, false);
    getTestBlocker().waitForSignals(1);
    assertEquals(2, callback.onLoadFinishedCount);
    assertEquals(0, callback.onErrorCount);
    assertEquals(0, callback.onLoadResetCount);
}

94. GeoUnmarshaller#unmarshal()

Project: apps-android-wikipedia
File: GeoUnmarshaller.java
@Nullable
public static Location unmarshal(@NonNull JSONObject jsonObj) {
    Location ret = new Location((String) null);
    ret.setLatitude(jsonObj.optDouble(LATITUDE));
    ret.setLongitude(jsonObj.optDouble(LONGITUDE));
    return ret;
}

95. NearbyUnitTests#testGetDistanceLabelKilometers()

Project: apps-android-wikipedia
File: NearbyUnitTests.java
public void testGetDistanceLabelKilometers() throws Exception {
    Location locationB = new Location("b");
    locationB.setLatitude(0.0d);
    locationB.setLongitude(LONGER_DISTANCE);
    assertEquals("1.11 km", getDistanceLabel(locationB));
}

96. NearbyUnitTests#testGetDistanceLabelMeters()

Project: apps-android-wikipedia
File: NearbyUnitTests.java
public void testGetDistanceLabelMeters() throws Exception {
    Location locationB = new Location("b");
    locationB.setLatitude(0.0d);
    locationB.setLongitude(SHORT_DISTANCE);
    assertEquals("111 m", getDistanceLabel(locationB));
}

97. NearbyUnitTests#testGetDistanceLabelSameLocation()

Project: apps-android-wikipedia
File: NearbyUnitTests.java
public void testGetDistanceLabelSameLocation() throws Exception {
    Location locationA = new Location("current");
    locationA.setLatitude(0.0d);
    locationA.setLongitude(0.0d);
    assertEquals("0 m", getDistanceLabel(locationA));
}

98. LocationField#set()

Project: androrm
File: LocationField.java
@Override
public void set(Cursor c, String fieldName) {
    double lat = c.getDouble(c.getColumnIndexOrThrow(latName(fieldName)));
    double lng = c.getDouble(c.getColumnIndexOrThrow(lngName(fieldName)));
    Location l = new Location(LocationManager.GPS_PROVIDER);
    l.setLatitude(lat);
    l.setLongitude(lng);
    mValue = l;
}

99. MapUserLocation#setDeviceLocation()

Project: Ushahidi_Android
File: MapUserLocation.java
protected void setDeviceLocation() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location lastNetLocation = null;
    Location lastGpsLocation = null;
    boolean netAvailable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    boolean gpsAvailable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!netAvailable && !gpsAvailable) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.location_disabled)).setMessage(getString(R.string.location_reenable)).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        }).create().show();
    }
    if (netAvailable) {
        lastNetLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    if (gpsAvailable) {
        lastGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }
    setBestLocation(lastNetLocation, lastGpsLocation);
    // network/GPS
    if (currrentLocation == null || (new Date()).getTime() - currrentLocation.getTime() > ONE_MINUTE) {
        if (netAvailable) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }
        if (gpsAvailable) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }
    }
}

100. LocationChangeSensor#onReceive()

Project: MozStumbler
File: LocationChangeSensor.java
public void onReceive(Context context, Intent intent) {
    if (intent == null || !intent.getAction().equals(GPSScanner.ACTION_GPS_UPDATED)) {
        return;
    }
    String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
    if (subject == null || !subject.equals(GPSScanner.SUBJECT_NEW_LOCATION)) {
        return;
    }
    Location newPosition = intent.getParcelableExtra(GPSScanner.NEW_LOCATION_ARG_LOCATION);
    if (newPosition == null) {
        return;
    }
    // Set the location time to current time instead of GPS time, as the remainder of the code
    // compares this time to current time, and we don't want 2 different time systems compared
    newPosition.setTime(sysClock.currentTimeMillis());
    if (mLastLocation == null) {
        ClientLog.d(LOG_TAG, "Received first location");
        mLastLocation = newPosition;
    } else {
        double dist = mLastLocation.distanceTo(newPosition);
        ClientLog.d(LOG_TAG, "Computed distance: " + dist);
        ClientLog.d(LOG_TAG, "Pref distance: " + mPrefMotionChangeDistanceMeters);
        boolean forceTimeout = intent.hasExtra(DEBUG_SEND_UNCHANGING_LOC);
        // TODO: this pref doesn't take into account the accuracy of the location.
        if (dist > mPrefMotionChangeDistanceMeters) {
            ClientLog.d(LOG_TAG, "Received new location exceeding distance changed in meters pref");
            mLastLocation = newPosition;
        } else if (isTimeWindowForMovementExceeded() || forceTimeout) {
            String log = "Insufficient movement:" + dist + " m, " + mPrefMotionChangeDistanceMeters + " m needed.";
            ClientLog.d(LOG_TAG, log);
            AppGlobals.guiLogInfo(log);
            LocalBroadcastManager.getInstance(mContext).sendBroadcastSync(new Intent(ACTION_LOCATION_NOT_CHANGING));
            removeTimeoutCheck();
            return;
        }
    }
    scheduleTimeoutCheck(mPrefMotionChangeTimeWindowMs);
}