英文:
Using a mock location provider in an espresso test on Android 11+
问题
我的Android应用程序使用GPS提供的位置信息。
我的某个类重写了LocationListener的onProviderDisabled
方法。
该应用程序正常运行并获取GPS位置。
我有一个Espresso测试,在测试类的@Before setup()方法中创建了一个用于模拟位置的测试提供程序:
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.addTestProvider(LOCATION_PROVIDER_NAME, false,
false, false, false,
true, true, true,
POWER_USAGE_HIGH,
ProviderProperties.ACCURACY_FINE);
locationManager.setTestProviderEnabled(LOCATION_PROVIDER_NAME, false);
然后在我的测试中,我调用:
locationManager.setTestProviderEnabled(LOCATION_PROVIDER_NAME, true);
SystemClock.sleep(200);
...
测试GPS是否已启用
...
在Android 8设备上,此代码正常工作(不会调用onProviderDisabled
)。
但是在Android 11、12和13设备上,在启用测试提供程序约300毫秒后,会调用onProviderDisabled
。
我需要在新的Android设备上启用模拟位置,我需要做什么?
英文:
My Android app uses the position provided by the gps.
One of my classes overrides the onProviderDisabled
method of LocationListener.
The app is working fine and gets the gps position.
I have an Espresso test that create a test provider for mock locations in the @Before setup() method of my test class:
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.addTestProvider(LOCATION_PROVIDER_NAME, false,
false, false, false,
true, true, true,
POWER_USAGE_HIGH,
ProviderProperties.ACCURACY_FINE);
locationManager.setTestProviderEnabled(LOCATION_PROVIDER_NAME, false);
Then in my test, I call
locationManager.setTestProviderEnabled(LOCATION_PROVIDER_NAME, true);
SystemClock.sleep(200);
...
test if gps is enabled
...
On an Android 8 device, this code works fine (onProviderDisabled
not called)
But on Android 11, 12 and 13 devices, about 300 ms after enabling the test provider, the onProviderDisabled
is called.
What do I need to do to enable mock location on new Android devices?
答案1
得分: 0
我终于找到了解决方法。当你知道它时,它就变得如此简单!在最近的Android设备上,在Espresso测试中使用虚拟位置时,你必须在运行测试之前手动打开位置服务。
注意:在Android 8设备上不需要这样做。
英文:
I finally found the solution. It is so easy when you know it !
On recent Android devices, when using mock locations in Espresso test, you must switch ON the location service manually before running the test.
Note: this was not required on Android 8 devices
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论