I use the code below to set a mock location without requiring the Location permission.
However, the code is inconsistent on Android devices with the latest Google Play Services version which utilizes the FusedLocationProviderClient
. Sometimes it works as intented, sometimes the location keeps jumping back and forth, sometimes it doesn't work at all. I also frequently get crashes with the error java.lang.IllegalArgumentException: Provider “gps” already exists
. Basically, it's bad code and I want to get rid of it in my app.
What I'm looking for is a full-proof solution that is able to successfuly fake the device's location (without requiring the Location permission), exactly like this Fake GPS app. I wish to re-create that app in Java. I haven't found anything online that fully works as of May 2020. I'd appreciate your help on that.
void setMockLocation() {
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.addTestProvider(LocationManager.GPS_PROVIDER, false, false,
false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
mockLocation.setLatitude(-33.852); // Sydney
mockLocation.setLongitude(151.211);
mockLocation.setAltitude(10);
mockLocation.setAccuracy(5);
mockLocation.setTime(System.currentTimeMillis());
mockLocation.setElapsedRealtimeNanos(System.nanoTime());
locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, mockLocation);
}