1

I'm trying to test GPS in Android, so I followed this recommendations Testing GPS in Android

My MainActivity class is like this:

public class MainActivity extends Activity implements LocationListener {
...
private LocationManager locationManager;
...

protected void onCreate(Bundle savedInstanceState) {
    ...
    this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    ...
}

...

protected void onResume() {
    ...
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    this.locationManager.requestLocationUpdates(Constants.GEOPOSITIONING_UPDATE_PERIOD,Constants.GEOPOSITIONING_UPDATE_DISTANCE, criteria, this, null);
    ...
}

...

public LocationManager getLocationManager() {
    return this.locationManager;
}

...
}

My test class is like this:

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
...
@UiThreadTest
public void test001() {
    LocationManager locationManager = null;

    try {
        MainActivity mainActivity = getActivity();

        locationManager = mainActivity.getLocationManager();
        locationManager.addTestProvider("Test", false, false, false, false, true, true, true, 0, 5);
        locationManager.setTestProviderEnabled("Test", true);

        Location location = new Location("Test");
        location.setLatitude(10.0);
        location.setLongitude(20.0);
        location.setAltitude(0);
        location.setTime(System.currentTimeMillis());
        location.setElapsedRealtimeNanos(System.currentTimeMillis());
        location.setAccuracy(Criteria.ACCURACY_FINE);
        locationManager.setTestProviderLocation("Test", location);

        ...
    } finally {
        if (locationManager != null) {
            locationManager.removeTestProvider("Test");
        }
    }
}

...
}

But the onLocationChanged of the MainActivity is never called, even after call setTestProviderLocation.

PS: I'm using the <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> permission in the manifest.

Community
  • 1
  • 1
csfb
  • 1,105
  • 1
  • 9
  • 19

2 Answers2

0

I wrote what I found here, check it out, it might help you as well.

Also, I noticed you are using "Test" as your test provider, but in your activity, you use requestLocationUpdates based on a criteria. This is another problem. You need to make sure the provider you are mocking your location is the same provider your application is expecting to receive callbacks from.

So if your Activity is waiting for locations from gps provider, you can't mock locations on Test provider and expect to receive them in the activity.

Hope it helps.

Community
  • 1
  • 1
m.hashemian
  • 1,786
  • 2
  • 15
  • 31
0

replace "Test" by LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER depending on which one you want to mock.