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

The following examples show how to use android.location.Location#setLatitude() . 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: TrackRecordingService.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Pauses the current track.
 */
private void pauseCurrentTrack() {
  if (!isRecording() || isPaused()) {
    Log.d(TAG, "Ignore pauseCurrentTrack. Not recording or paused.");
    return;
  }

  // Update shared preferences
  recordingTrackPaused = true;
  PreferencesUtils.setBoolean(this, R.string.recording_track_paused_key, true);

  // Update database
  Track track = myTracksProviderUtils.getTrack(recordingTrackId);
  if (track != null) {
    insertLocation(track, lastLocation, getLastValidTrackPointInCurrentSegment(track.getId()));

    Location pause = new Location(LocationManager.GPS_PROVIDER);
    pause.setLongitude(0);
    pause.setLatitude(PAUSE_LATITUDE);
    pause.setTime(System.currentTimeMillis());
    insertLocation(track, pause, null);
  }

  endRecording(false, recordingTrackId);
}
 
Example 2
Source File: ReplayJsonRouteLocationMapper.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
private List<Location> mapReplayLocations() {
  List<Location> locations = new ArrayList<>(replayLocations.size());
  for (ReplayLocationDto sample : replayLocations) {
    Location location = new Location(REPLAY);
    location.setLongitude(sample.getLongitude());
    location.setAccuracy(sample.getHorizontalAccuracyMeters());
    location.setBearing((float) sample.getBearing());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      location.setVerticalAccuracyMeters(sample.getVerticalAccuracyMeters());
    }
    location.setSpeed((float) sample.getSpeed());
    location.setLatitude(sample.getLatitude());
    location.setAltitude(sample.getAltitude());
    Date date = sample.getDate();
    if (date != null) {
      location.setTime(date.getTime());
    }
    locations.add(location);
  }
  return locations;
}
 
Example 3
Source File: TrackStubUtils.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link MyTracksLocation} stub with specified values.
 * 
 * @return a MyTracksLocation stub.
 */
public static MyTracksLocation createMyTracksLocation(double latitude, double longitude,
    double altitude) {
  // Initial Location
  Location loc = new Location(LOCATION_PROVIDER);
  loc.setLatitude(latitude);
  loc.setLongitude(longitude);
  loc.setAltitude(altitude);
  loc.setAccuracy(INITIAL_ACCURACY);
  loc.setSpeed(INITIAL_SPEED);
  loc.setTime(INITIAL_TIME);
  loc.setBearing(INITIAL_BEARING);
  SensorDataSet sd = SensorDataSet.newBuilder().build();
  MyTracksLocation myTracksLocation = new MyTracksLocation(loc, sd);

  return myTracksLocation;
}
 
Example 4
Source File: WeatherUpdateWorker.java    From PixelWatchFace with GNU General Public License v3.0 6 votes vote down vote up
private boolean shouldUpdateWeatherProvider(Location currentLocation) {
  Location lastLocation = new Location(
      mSharedPreferences.getString(KEY_LAST_LOCATION + KEY_LOCATION_PROVIDER, ""));
  lastLocation.setLongitude(
      mSharedPreferences.getFloat(KEY_LAST_LOCATION + KEY_LONGITUDE, Float.MIN_VALUE));
  lastLocation.setLatitude(
      mSharedPreferences.getFloat(KEY_LAST_LOCATION + KEY_LATITUDE, Float.MIN_VALUE));
  lastLocation.setAltitude(mSharedPreferences.getFloat(KEY_LAST_LOCATION + KEY_ALTITUDE, 0));

  String lastWeatherProviderTypeJSON = mSharedPreferences
      .getString(KEY_LAST_WEATHER_PROVIDER, "");

  if (lastWeatherProviderTypeJSON.isEmpty() || !isLocationValid(lastLocation)) {
    return true;
  } else {
    return currentLocation.distanceTo(lastLocation) >= WEATHER_PROVIDER_DISTANCE_UPDATE_THRESHOLD;
  }
}
 
Example 5
Source File: EarthquakeTypeConverters.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@TypeConverter
public static Location locationFromString(String location) {
  if (location != null && (location.contains(","))) {
    Location result = new Location("Generated");
    String[] locationStrings = location.split(",");

    if (locationStrings.length == 2) {
      result.setLatitude(Double.parseDouble(locationStrings[0]));
      result.setLongitude(Double.parseDouble(locationStrings[1]));
      return result;
    }
    else return null;
  }
  else
    return null;
}
 
Example 6
Source File: ExportAllAndImportAllTest.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the GPX file distance in km.
 */
private double getGpxFileDistance() {
  double distance = 0.0;
  double latitude = GPX_FILE_INIT_LATITUDE;
  double longitude = GPX_FILE_INIT_LONGITUDE;

  Location current = new Location(LocationManager.GPS_PROVIDER);
  current.setLatitude(latitude);
  current.setLongitude(longitude);
  for (int i = 1; i < 10; i++) {
    Location next = new Location(LocationManager.GPS_PROVIDER);
    next.setLatitude(latitude - 0.0005 * i);
    next.setLongitude(longitude + 0.0005 * i);
    distance = distance + next.distanceTo(current) * UnitConversions.M_TO_KM;
    current = next;
  }
  return distance;
}
 
Example 7
Source File: MainFragment.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
private void calcQiblaAngle(@NonNull Location location) {
    mLocation = location;
    if (!"custom".equals(location.getProvider())) {
        mSelCity.setVisibility(View.GONE);
    }
    double lat1 = location.getLatitude();// Latitude of User Location
    double lng1 = location.getLongitude();// Longitude of User Location
    double lat2 = 21.42247;// Latitude of Qaaba (+21.45° north of Equator)
    double lng2 = 39.826198;// Longitude of Qaaba (-39.75° east of Prime Meridian)

    double q = -getDirection(lat1, lng1, lat2, lng2);

    Location loc = new Location(location);
    loc.setLatitude(lat2);
    loc.setLongitude(lng2);
    mQiblaAngle = q;
    mQiblaDistance = location.distanceTo(loc) / 1000;

    notifyListener();

}
 
Example 8
Source File: RequestTests.java    From FacebookImageShareIntent with MIT License 6 votes vote down vote up
@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);

    assertNotNull(response.getRawResponse());
}
 
Example 9
Source File: DrawPathTaskTest.java    From open with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    application = (TestMapzenApplication) Robolectric.application;
    application.inject(this);
    TestHelper.initBaseActivity();
    TestMap testMap = (TestMap) mapController.getMap();
    viewController = Mockito.mock(ViewController.class);
    testMap.setViewport(viewController);
    task = new DrawPathTask(application);
    box = Mockito.mock(BoundingBox.class);
    stub(viewController.getBBox()).toReturn(box);
    outsideBefore1 = new Location("f");
    outsideBefore1.setLatitude(1);
    outsideBefore2 = new Location("f");
    outsideBefore2.setLatitude(2);
    inside1 = new Location("f");
    inside1.setLatitude(3);
    inside2 = new Location("f");
    inside2.setLatitude(4);
    outSideAfter1 = new Location("f");
    outSideAfter1.setLatitude(5);
    outSideAfter2 = new Location("f");
    outSideAfter2.setLatitude(6);
}
 
Example 10
Source File: CbService.java    From PressureNet-SDK with MIT License 6 votes vote down vote up
/**
 * Make a CbApiCall object for local conditions
 * @return
 */
public CbApiCall buildLocalConditionsApiCall() {
	CbApiCall conditionApiCall = new CbApiCall();
	conditionApiCall.setCallType("Conditions");
	Location location = new Location("network");
	location.setLatitude(0);
	location.setLongitude(0);
	if(locationManager != null) {
		location = locationManager.getCurrentBestLocation();
		if(location != null) {
			conditionApiCall.setMinLat(location.getLatitude() - .1);
			conditionApiCall.setMaxLat(location.getLatitude() + .1);
			conditionApiCall.setMinLon(location.getLongitude() - .1);
			conditionApiCall.setMaxLon(location.getLongitude() + .1);
			conditionApiCall.setStartTime(System.currentTimeMillis() - (1000 * 60 * 60));
			conditionApiCall.setEndTime(System.currentTimeMillis());
			return conditionApiCall;
		} else {
			return null;
		}
	} else {
		log("cbservice not checking location condition reports, no locationmanager");
		return null;
	}
}
 
Example 11
Source File: LocationTracker.java    From Android-SDK with MIT License 5 votes vote down vote up
private Location getSavedLocation()
  {
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences( getApplicationContext() );
//    String locationStr = sharedPref.getString( LOCATION, null );
    String locationLatitudeString = sharedPref.getString( LOCATION_LATITUDE_TAG, null );
    String locationLongitudeString = sharedPref.getString( LOCATION_LONGITUDE_TAG, null );
    Location savedLocation = new Location( provider );

//    if( locationStr == null )
//    {
//      return null;
//    }

    if( locationLatitudeString == null || locationLongitudeString == null )
      return null;

    try
    {
      savedLocation.setLatitude( (Double) Serializer.fromBytes( Base64.decode( locationLatitudeString, Base64.DEFAULT ), ISerializer.AMF3, false ) );
      savedLocation.setLongitude( (Double) Serializer.fromBytes( Base64.decode( locationLongitudeString, Base64.DEFAULT ), ISerializer.AMF3, false ) );
      return savedLocation;
//      return (Location) Serializer.fromBytes( Base64.decode( locationStr, Base64.DEFAULT ), ISerializer.AMF3, false );
    }
    catch( IOException e )
    {
      Log.e( "Cannot get location", e.getMessage() );
      return null;
    }
  }
 
Example 12
Source File: SendMapsUtilsTest.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
 * Location)} with a null title.
 */
public void testBuildMapsMarkerFeature_null_title() {
  Location location = new Location("test");
  location.setLatitude(123.0);
  location.setLongitude(456.0);
  MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
      null, "description", "url", location);
  assertEquals(MapsFeature.MARKER, mapFeature.getType());
  assertNotNull(mapFeature.getAndroidId());
  assertEquals("-", mapFeature.getTitle());
  assertEquals("description", mapFeature.getDescription());
  assertEquals("url", mapFeature.getIconUrl());
  assertEquals(123.0, mapFeature.getPoint(0).getLatitude());
  assertEquals(456.0, mapFeature.getPoint(0).getLongitude());
}
 
Example 13
Source File: LocationInfo.java    From Androzic with GNU General Public License v3.0 5 votes vote down vote up
private void updateLocationInfo(View view)
{

	Androzic application = Androzic.getApplication();

	Location loc = new Location("fake");
	loc.setLatitude(location[0]);
	loc.setLongitude(location[1]);

	((TextView) view.findViewById(R.id.coordinate_degree)).setText(StringFormatter.coordinates(0, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_degmin)).setText(StringFormatter.coordinates(1, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_degminsec)).setText(StringFormatter.coordinates(2, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_utmups)).setText(StringFormatter.coordinates(3, " ", location[0], location[1]));
	((TextView) view.findViewById(R.id.coordinate_mgrs)).setText(StringFormatter.coordinates(4, " ", location[0], location[1]));

	Calendar now = GregorianCalendar.getInstance(TimeZone.getDefault());
	double sunrise = Astro.computeSunriseTime(application.getZenith(), loc, now);
	double sunset = Astro.computeSunsetTime(application.getZenith(), loc, now);

	if (Double.isNaN(sunrise))
	{
		((TextView) view.findViewById(R.id.sunrise)).setText(R.string.never);
	}
	else
	{
		((TextView) view.findViewById(R.id.sunrise)).setText(Astro.getLocalTimeAsString(sunrise));
	}
	if (Double.isNaN(sunset))
	{
		((TextView) view.findViewById(R.id.sunset)).setText(R.string.never);
	}
	else
	{
		((TextView) view.findViewById(R.id.sunset)).setText(Astro.getLocalTimeAsString(sunset));
	}
	double declination = application.getDeclination(location[0], location[1]);
	((TextView) view.findViewById(R.id.declination)).setText(String.format("%+.1f\u00B0", declination));
}
 
Example 14
Source File: ContentProviderLocationDAOTest.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testPersistLocation() {
    LocationDAO dao = new ContentProviderLocationDAO(getContext());

    Location location = new Location("fake");
    location.setAccuracy(200);
    location.setAltitude(900);
    location.setBearing(2);
    location.setLatitude(40.21);
    location.setLongitude(23.45);
    location.setSpeed(20);
    location.setProvider("test");
    location.setTime(1000);
    BackgroundLocation bgLocation = BackgroundLocation.fromLocation(location);

    dao.persistLocation(bgLocation);

    ArrayList<BackgroundLocation> locations = new ArrayList(dao.getAllLocations());
    assertEquals(1, locations.size());

    BackgroundLocation storedLocation = locations.get(0);
    assertEquals(200, storedLocation.getAccuracy(), 0);
    assertEquals(900, storedLocation.getAltitude(), 0);
    assertEquals(2, storedLocation.getBearing(), 0);
    assertEquals(40.21, storedLocation.getLatitude(), 0);
    assertEquals(23.45, storedLocation.getLongitude(), 0);
    assertEquals(20, storedLocation.getSpeed(), 0);
    assertEquals("test", storedLocation.getProvider(), "test");
    assertEquals(1000, storedLocation.getTime(), 0);
    junit.framework.Assert.assertFalse(storedLocation.hasMockLocationsEnabled());
    junit.framework.Assert.assertFalse(storedLocation.areMockLocationsEnabled());
    junit.framework.Assert.assertTrue(storedLocation.hasIsFromMockProvider()); // because setIsFromMockProvider is called in constructor
    junit.framework.Assert.assertFalse(storedLocation.isFromMockProvider());
}
 
Example 15
Source File: Mapa.java    From android with GNU General Public License v2.0 5 votes vote down vote up
public void onClick(View v) {
	
	switch (v.getId()) {
	case R.id.btGuardarPosicion:
		// Guarda la posición actual en la Base de Datos
		Location location = mapa.getMyLocation();
           if (location != null) {
               Ubicacion ubicacion = new Ubicacion();
               ubicacion.setNombre("Desde Mapa");
               ubicacion.setPosicion(new LatLng(location.getLatitude(), location.getLongitude()));
               database.nuevaUbicacion(ubicacion);
           }
           else {
               Toast.makeText(this, R.string.sinubicacion_message, Toast.LENGTH_SHORT).show();
           }
		break;
	case R.id.btVerMiPosicion:
		// TODO
		break;
	case R.id.btDistancia:
		// Calcula la distancia en metros entre la posición actual y la última marca pulsada
		Location yo = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if ((marker != null) && (yo != null)) {
			Location loc = new Location(marker.getTitle());
			loc.setLatitude(marker.getPosition().latitude);
			loc.setLongitude(marker.getPosition().longitude);
			
			Toast.makeText(this, String.valueOf(yo.distanceTo(loc)), Toast.LENGTH_LONG).show();
		}
           else {
               Toast.makeText(this, R.string.distancia_error_message, Toast.LENGTH_LONG).show();
           }
		
		break;
	default:
		break;
	}
}
 
Example 16
Source File: LocationUtils.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Helper method for creating a new Location object with the specified latitude and longitude.
 * Android's Location class doesn't have a nice constructor or builder.
 *
 * @param lat Latitude of location.
 * @param lon Longitude of location.
 * @return New location object.
 */
@NonNull
public static Location buildLocation(double lat, double lon) {
    Location location = new Location(""); // Blank location provider name
    location.setLatitude(lat);
    location.setLongitude(lon);

    return location;
}
 
Example 17
Source File: SettingsFragment.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ACTIVITY_PICKPLACE && resultCode == Activity.RESULT_OK) {
        Place place = PlacePicker.getPlace(getActivity(), data);
        final CharSequence name = place.getName();
        LatLng ll = place.getLatLng();
        if (name == null || ll == null)
            return;

        // Build location
        final Location location = new Location("place");
        location.setLatitude(ll.latitude);
        location.setLongitude(ll.longitude);
        location.setTime(System.currentTimeMillis());

        // Get settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        final boolean altitude_waypoint = prefs.getBoolean(PREF_ALTITUDE_WAYPOINT, DEFAULT_ALTITUDE_WAYPOINT);

        new AsyncTask<Object, Object, Object>() {
            protected Object doInBackground(Object... params) {
                int altitude_type = (location.hasAltitude() ? BackgroundService.ALTITUDE_GPS : BackgroundService.ALTITUDE_NONE);

                // Add elevation data
                if (!location.hasAltitude() && Util.isConnected(getActivity())) {
                    if (altitude_waypoint)
                        try {
                            GoogleElevationApi.getElevation(location, getActivity());
                            altitude_type = BackgroundService.ALTITUDE_LOOKUP;
                        } catch (Throwable ex) {
                            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        }
                }

                if (altitude_type != BackgroundService.ALTITUDE_NONE)
                    altitude_type |= BackgroundService.ALTITUDE_KEEP;

                // Persist location
                new DatabaseHelper(getActivity()).insertLocation(location, altitude_type, name.toString()).close();
                return null;
            }

            @Override
            protected void onPostExecute(Object result) {
                if (running)
                    Toast.makeText(getActivity(), getString(R.string.msg_added, name.toString()), Toast.LENGTH_SHORT).show();
            }
        }.execute();

    } else if (requestCode == ACTIVITY_PLAY_SERVICES)
        ; // Do nothing

    else
        super.onActivityResult(requestCode, resultCode, data);
}
 
Example 18
Source File: LocationAdapter.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    final long time = cursor.getLong(colTime);
    final String provider = cursor.getString(colProvider);
    final double latitude = cursor.getDouble(colLatitude);
    final double longitude = cursor.getDouble(colLongitude);
    final boolean hasAltitude = !cursor.isNull(colAltitude);
    boolean hasBearing = !cursor.isNull(colBearing);
    boolean hasAccuracy = !cursor.isNull(colAccuracy);
    double altitude = cursor.getDouble(colAltitude);
    double bearing = cursor.getDouble(colBearing);
    double accuracy = cursor.getDouble(colAccuracy);
    final String name = cursor.getString(colName);

    // Calculate distance to last location
    Location dest = new Location("");
    dest.setLatitude(latitude);
    dest.setLongitude(longitude);
    double distance = (lastLocation == null ? 0 : lastLocation.distanceTo(dest));

    // Get views
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    ImageView ivWaypoint = (ImageView) view.findViewById(R.id.ivWaypoint);
    TextView tvProvider = (TextView) view.findViewById(R.id.tvProvider);
    TextView tvAltitude = (TextView) view.findViewById(R.id.tvAltitude);
    ImageView ivBearing = (ImageView) view.findViewById(R.id.ivBearing);
    TextView tvAccuracy = (TextView) view.findViewById(R.id.tvAccuracy);
    TextView tvDistance = (TextView) view.findViewById(R.id.tvDistance);

    // Set values
    tvTime.setText(
            new SimpleDateFormat("dd").format(time) + " " +
                    SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT).format(time));
    ivWaypoint.setVisibility(name == null ? View.INVISIBLE : View.VISIBLE);

    int resId = context.getResources().getIdentifier("provider_" + provider, "string", context.getPackageName());
    tvProvider.setText(resId == 0 ? "-" : context.getString(resId).substring(0, 1));
    tvAltitude.setText(hasAltitude ? Long.toString(Math.round(altitude)) : "?");

    if (hasBearing) {
        ivBearing.setRotation((float) bearing - 90);
        ivBearing.setVisibility(View.VISIBLE);
    } else
        ivBearing.setVisibility(View.INVISIBLE);

    tvAccuracy.setText(hasAccuracy ? Long.toString(Math.round(accuracy)) : "?");
    if (lastLocation != null && distance >= 1e7)
        tvDistance.setText(Long.toString(Math.round(distance / 1e6)) + "M");
    else if (lastLocation != null && distance >= 1e4)
        tvDistance.setText(Long.toString(Math.round(distance / 1e3)) + "k");
    else
        tvDistance.setText(lastLocation == null ? "?" : Long.toString(Math.round(distance)));
}
 
Example 19
Source File: LocationServiceTest.java    From background-geolocation-android with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 5000)
public void testOnLocationOnStoppedService() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(3);
    BroadcastReceiver serviceBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            int action = bundle.getInt("action");

            if (action == LocationServiceImpl.MSG_ON_SERVICE_STARTED) {
                latch.countDown();
                mService.stop();
                //mService.onDestroy();
            }
            if (action == LocationServiceImpl.MSG_ON_SERVICE_STOPPED) {
                latch.countDown();
                mService.onLocation(new BackgroundLocation());
            }
            if (action == LocationServiceImpl.MSG_ON_LOCATION) {
                latch.countDown();
            }
        }
    };

    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(InstrumentationRegistry.getTargetContext());
    lbm.registerReceiver(serviceBroadcastReceiver, new IntentFilter(LocationServiceImpl.ACTION_BROADCAST));

    Config config = Config.getDefault();
    config.setStartForeground(false);

    MockLocationProvider provider = new MockLocationProvider();
    Location location = new Location("gps");
    location.setProvider("mock");
    location.setElapsedRealtimeNanos(2000000000L);
    location.setAltitude(100);
    location.setLatitude(49);
    location.setLongitude(5);
    location.setAccuracy(105);
    location.setSpeed(50);
    location.setBearing(1);

    provider.setMockLocations(Arrays.asList(location));
    mLocationProviderFactory.setProvider(provider);

    mService.setLocationProviderFactory(mLocationProviderFactory);
    mService.configure(config);
    mService.start();

    latch.await();
    lbm.unregisterReceiver(serviceBroadcastReceiver);
}
 
Example 20
Source File: Utils.java    From android-utils with MIT License 4 votes vote down vote up
/**
 * 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) {
    // use application level context to avoid unnecessary leaks.
    LocationManager locationManager = (LocationManager) ctx.getApplicationContext().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);
}