【问题标题】:Enable/Disable wifi using Xamarin UiTest使用 Xamarin UiTest 启用/禁用 wifi
【发布时间】:2018-05-16 07:22:48
【问题描述】:

我尝试在我的 Xamarin Ui 测试中以编程方式启用/禁用 wifi。
我已经找到了这个:Android: How to Enable/Disable Wifi or Internet Connection Programmatically。但它似乎不适用于 UiTest。

我也尝试过这样的事情:

Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(Context.WifiService);
bool status = false;
wifiManager.SetWifiEnabled(status);

第一行(Android.App.Application.Context)抛出异常:

Message: System.IO.FileNotFoundException : Could not load file or assembly 'Java.Interop, Version=0.1.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065' or one of its dependencies. The system cannot find the file specified.

我正在使用以下命名空间:

using Android.Net.Wifi;
using Android.Content;

我的项目引用了Mono.Android

【问题讨论】:

  • 将其作为方法添加到您的Xamarin.Android 项目中,并将其公开为可以通过 UITest 代码调用的后门。

标签: android xamarin xamarin.uitest


【解决方案1】:

后门方法对我来说很好。

对我有用的解决方案是:

1.:在 Android 项目的 AndroidManifest.xml 文件中添加以下行:

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

2.:在 Android 项目的 MainActivity.cs 中添加以下行:

using Java.Interop;
using Android.Net.Wifi;

[Export("ChangeWifiState")]
public void ChangeWifiState(bool state)
{
    Context appContext = Android.App.Application.Context;
    var wifiManager = (WifiManager)appContext.GetSystemService(WifiService);
    wifiManager.SetWifiEnabled(state);
}

3.:从 Xamarin Ui 测试中调用以下方法:

app.Invoke("ChangeWifiState", false);    // true to enable wifi, false to disable wifi

PS:我使用 Xamarin 表单。我有四个不同的项目:一个核心项目、一个 Android 项目、一个 Ui 项目和一个测试项目。

我刚刚找到了第二个解决方案,而不使用实际的应用程序。
它使用 ADB 命令来启用/禁用 wifi:

        var process = new System.Diagnostics.Process();
        var startInfo = new System.Diagnostics.ProcessStartInfo
        {
            WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
            FileName = "cmd.exe",
            Arguments = "/C adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings adb shell input keyevent 19 & adb shell input keyevent 19 & adb shell input keyevent 23 & adb shell input keyevent 82 & adb shell input tap 500 1000"
        };
        process.StartInfo = startInfo;
        process.Start();

这可以在没有根设备的情况下使用:)。
步骤说明:
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings 打开 wifi 设置。
adb shell input keyevent 23 启用/禁用 wifi。
我不确定为什么要使用命令adb shell input keyevent 19,但它可以工作。
adb shell input keyevent 82 单击菜单按钮以更改回原始应用程序。
adb shell input tap 500 1000 单击坐标 x=500, y =1000(屏幕中心)。这可能需要针对不同的解决方案进行更改。
此解决方案的来源:

【讨论】:

  • 由于某些原因,这个解决方案不再适用于我的新 Android 8.1。
    因此我更改了两件事:
    1. 将“keyevent 82”替换为菜单按钮(可能是 8.1 的安全更新)
    2. 将大参数拆分为 3 个小参数(1:打开设置,2:更改状态,3:返回原始应用)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
相关资源
最近更新 更多