使用Xamarin UiTest启用/禁用wifi

时间:2018-05-16 07:22:49

标签: android xamarin xamarin.uitest

我尝试在我的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

1 个答案:

答案 0 :(得分:4)

后门方法对我来说很好。

对我有用的解决方案是:

的组合

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 Forms。我有四个不同的项目:核心项目,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();

这可以在没有root设备的情况下使用:)。
步骤说明:
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(屏幕中心)。这可能需要针对不同的解决方案进行更改。
此解决方案的来源:

相关问题