lamecoder lamecoder - 1 year ago 113
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):

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);

t = new Timer();

t.scheduleAtFixedRate(new TimerTask() {
public void run() {
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
}, 0, 2000);

}catch(SecurityException e){

I have tried removing the mocked location provider with:

lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, false);

if (lm.getProvider(LocationManager.GPS_PROVIDER) != null){
Log.i("REMOVE", "test 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 Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download