我目前正在开发一个涵盖离线功能的 Espresso 测试套件。为了实现这些测试,我需要创建一个可以调用来打开/关闭网络连接的方法。到目前为止,我已经能够切换 WiFi,但我还不知道如何关闭蜂窝数据。
非常感谢任何信息。
您还可以执行really卡顿解决方法。 注意:我这样做主要是为了好玩,不提倡实际使用;)
#!/bin/bash
### SET Airplane Mode ON ###
adb shell am start -a android.settings.AIRPLANE_MODE_SETTINGS \
&& for i in {1..5}
do
adb shell input keyevent 20
done \
&& adb shell input keyevent 23 \
&& adb shell input keyevent 4;
### Run tests ###
### SET Airplane Mode OFF ###
# NOTE: When Airplane Mode is enabled in API 28, "Mobile network" is disabled. Additionally, since Android Setting's Network & internet
# is still running in the background, you'll have to select the down action two less times.
adb shell am start -a android.settings.AIRPLANE_MODE_SETTINGS \
&& for i in {1..3}
do
adb shell input keyevent 20
done \
&& adb shell input keyevent 23 \
&& adb shell input keyevent 4;
尝试@zzz 的解决方案
(请在 https://stackoverflow.com/a/53414845/191761 上投票支持他们的答案)
public static void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}
@Illyct 的另一个想法,可以通过 shell 关闭 WiFi 和移动数据:
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc wifi disable")
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc data disable")
我测试了它,它对我有用。
请参阅他们的答案。