我的应用程序运行良好,但现在我必须测试一个通过 LocationManager 获取位置的类,所以我决定在清单中激活模拟位置:
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
tools:ignore="ProtectedPermissions" />
我还在模拟器(开发设置)上激活了模拟位置。这是我使用 LocationManager 的方法:
public Location getCurrentLocation() {
try {
LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}
return locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (NullPointerException e) {
return null;
}
}
这是我的测试课:
public class LocationTest {
Context context;
@Rule
public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.ACCESS_FINE_LOCATION);
@Before
public void init() {
context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Location mockLocation = new Location(android.location.LocationManager.GPS_PROVIDER);
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.addTestProvider(android.location.LocationManager.GPS_PROVIDER, false, false,
false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(android.location.LocationManager.GPS_PROVIDER, true);
mockLocation.setLatitude(-20.000);
mockLocation.setLongitude(10.000);
mockLocation.setAltitude(10);
mockLocation.setBearing(0);
mockLocation.setAccuracy(5);
mockLocation.setSpeed(0);
mockLocation.setTime(System.currentTimeMillis());
mockLocation.setElapsedRealtimeNanos(System.nanoTime());
locationManager.setTestProviderStatus(android.location.LocationManager.GPS_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
locationManager.setTestProviderLocation(android.location.LocationManager.GPS_PROVIDER, mockLocation);
}
@After
public void tearDown() {
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeTestProvider(android.location.LocationManager.GPS_PROVIDER);
}
@Test
public void getCurrentLocationTest() {
LocationClass locClass = new LocationClass(context);
Location loc = locClass.getCurrentLocation();
assertFalse(loc == null);
}
}
出于某种原因,“返回 locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);” 在 getCurrentLocation() 中始终返回 null(不抛出异常,并且授予权限)。
当我启动我的应用程序时它可以工作,但是当我尝试在测试中模拟位置,甚至在不模拟位置的情况下尝试它时,LocationManager 没有找到任何位置(虽然激活模拟位置有效 -> 没有抛出异常,只是经理赢了'不检测任何位置)。
我什至可以模拟仪表测试的位置并使用 getLastKnownLocation 返回它吗?我该怎么做才能让它发挥作用?