无法切换飞行模式,浓缩咖啡



我正在尝试在kitkat 版本有根模拟器上切换飞行模式。我正在使用浓缩咖啡进行自动化,在这种情况下,我必须打开飞行模式并在应用程序中执行某种步骤

我使用以下方法修改了时间:

public static void amTime() {
try {
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes("date -s 20181015.070000");
outputStream.flush();
outputStream.writeBytes("exitn");
outputStream.flush();
su.wait(2000);
} catch (Exception e){
Log.e("Set Time", e.getMessage());
}
}

但是我无法切换到飞行模式,我已经尝试了不同的模式......使用了上述方法并使用 adb 命令修改了以下行

outputStream.writeBytes("mode airplane_mode_on 1");
outputStream.writeBytes("adb shell -c settings put global airplane_mode_on 1");
outputStream.writeBytes("adb shell -c settings put global airplane_mode_on 0");

有人可以帮忙编写代码或 adb 脚本,通过它我可以打开和关闭飞行模式

只需按如下方式创建方法,并在需要时调用:

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);
}

调用该方法:

try {
CommonUtil.setMobileDataEnabled(mActivityTestRule.getActivity().getApplicationContext(),true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

请注意,这将设置数据启用=关闭..这是我的要求。

我从@Illyct中找到的另一种解决方案:

InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("svc data disable")

请在 https://stackoverflow.com/a/64765567/191761 对他们的回答投赞成票

最新更新