问题描述
我的应用程序运行良好,但现在我必须测试一个通过 LocationManager 获取位置的类,所以我决定在清单中激活模拟位置:
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
tools:ignore="ProtectedPermissions" />
而且我还激活了模拟器上的 Mock Location(开发设置)。 这是我使用 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,true,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 找不到位置(尽管激活模拟位置有效 -> 没有抛出异常,只是Manager 不会检测到任何位置)。
我什至可以模拟 Instrumented 测试的位置并使用 getLastKNownLocation 返回它吗?我可以尝试做些什么来让它发挥作用?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)