Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

android - setTestProviderLocation() does not trigger calling of onLocationChanged()

I'm trying to get this bit of code to work:

Testing GPS in Android

The problem is, when I run the test, onLocationChanged() is never called:

public class LocationTest0 extends AndroidTestCase implements LocationListener {
private Location received = null;
public void testExample() {
    LocationManager lm = (LocationManager)this.getContext().getSystemService(Context.LOCATION_SERVICE);
    String testProvider = "Test";

    if (null == lm.getProvider(testProvider)){
        lm.addTestProvider(testProvider, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
    }

    lm.setTestProviderEnabled(testProvider, true);
    lm.requestLocationUpdates(testProvider, 0, 0, this);
    lm.setTestProviderStatus(testProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());

    Location location = new Location(testProvider);
    location.setLatitude(1.0);
    location.setLongitude(2.0);
    location.setTime(System.currentTimeMillis());
    lm.setTestProviderLocation(testProvider, location);

    Assert.assertFalse("Received Location is null", received == null );

    lm.removeTestProvider(testProvider);
}
@Override
public void onLocationChanged(Location location) {
    received = location;
    Log.d("LocationTest0", "onLocationChanged CALLED");
    // Never gets called
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what worked for me

locationManager.addTestProvider(mocLocationProvider, false, false,
                    false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);

.

Location mockLocation = new Location(mocLocationProvider); // a string
mockLocation.setLatitude(location.getLatitude());  // double 
mockLocation.setLongitude(location.getLongitude()); 
mockLocation.setAltitude(location.getAltitude()); 
mockLocation.setTime(System.currentTimeMillis()); 
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation); 

.

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">

Also in the android phone settings make sure you have the "Allow mock locations" checkbox ticked


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...