CL2*_*L22 5 junit android locationmanager
我正在尝试使用这段代码:
问题是,当我运行测试时,永远不会调用onLocationChanged():
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
}
Run Code Online (Sandbox Code Playgroud)
这对我有用
locationManager.addTestProvider(mocLocationProvider, false, false,
false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
Run Code Online (Sandbox Code Playgroud)
.
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);
Run Code Online (Sandbox Code Playgroud)
.
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">
Run Code Online (Sandbox Code Playgroud)
同样在Android手机设置中,请确保勾选"允许模拟位置"复选框
| 归档时间: |
|
| 查看次数: |
6050 次 |
| 最近记录: |