lamecoder lamecoder - 2 months ago 8
Android Question

Reset location provider to use actual GPS after mocking location

As a coding newbie, this is my first SO question so apologies if it's a little rough around the edges and the code is less than epic.

I'm mocking locations in Android and I am able to successfully mock the GPS_PROVIDER. However when my mocking app is not running, the location does not return to the user's actual position. Is there a way to stop mocking locations so that the real GPS position returns and updates as normal?

The code I am using to mock locations is (extract from activity):

try
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 50, 0, lis);

lm.addTestProvider(LocationManager.GPS_PROVIDER, false, false, false, false, true, true, true, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);

loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(51.5219145);
loc.setLongitude(-0.1285495);
loc.setTime(System.currentTimeMillis());
loc.setAccuracy(10);
loc.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());


t = new Timer();

t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
loc.setTime(System.currentTimeMillis());
loc.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
}
}, 0, 2000);

}catch(SecurityException e){
e.printStackTrace();
}


I have tried removing the mocked location provider with:

lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, false);
lm.clearTestProviderLocation(LocationManager.GPS_PROVIDER);

if (lm.getProvider(LocationManager.GPS_PROVIDER) != null){
Log.i("REMOVE", "test provider");
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
}


The above does run but doesn't seem to do anything. I suspect that I have replaced the default location provider. Is there a way to restore it? I'd appreciate any advice you could offer. Thanks.

Answer
 lm.removeTestProvider(LocationManager.GPS_PROVIDER);

When remove the provider, just let Gps to receive fresh location, then it will be fixed. You can test it

  1. Set your mock location for Gps
  2. Go to GoogleMaps and see your mock location (Gps must be enabled)
  3. Turn back your app and stop mocking
  4. Go again GoogleMaps, and wait until Gps provider receive a real location. It could take a bit time, when i tested in home, taken 1-2 minutes but in balcony just 5 seconds.