8

I want to switch on wifi as a part of test case using uiautomator tool in android. I tried using following code in uiautomator test case:

WifiManager wi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
      if(wi.isWifiEnabled()){
        wi.setWifiEnabled(false);
      }else{
        wi.setWifiEnabled(true);
    }

but it gave this error:

"getSystemservice" method is undefined for Mainclass

levelnis
  • 7,665
  • 6
  • 37
  • 61
user1907534
  • 79
  • 1
  • 2

6 Answers6

9

You can actually use UIAutomator to set the WiFi setting on and off. I wrote the code this evening :)

Here's the code. You can add it to the Android example which is here http://developer.android.com/tools/testing/testing_ui.html

Add the following enum at the top of the class

private enum OnOff {
    Off,
    On
};

Add the new code after:

    // Validate that the package name is the expected one
    UiObject settingsValidation = new UiObject(new UiSelector()
    .packageName("com.android.settings"));
    assertTrue("Unable to detect Settings", settingsValidation.exists());

Here is the new code:

    UiSelector settingsItems = new UiSelector().className(android.widget.TextView.class.getName());
    UiObject wiFi = appViews.getChildByText(settingsItems, "Wi-Fi");

    // We can click on Wi-Fi, e.g. wiFi.clickAndWaitForNewWindow();
    // So we know we have found the Wi-Fi setting

    UiSelector switchElement = new UiSelector().className(android.widget.Switch.class.getName());
    setSwitchTo(OnOff.Off); // Or set it to On as you wish :)
}   

private void setSwitchTo(OnOff value) throws UiObjectNotFoundException {

    String text;
    UiObject switchObject = getSwitchObject();
    for (int attempts = 0; attempts < 5; attempts++) {
        text = switchObject.getText();
        boolean switchIsOn = switchObject.isChecked();
        final OnOff result;
        if (switchIsOn) {
            result = OnOff.On;
        } else {
            result = OnOff.Off;
        }

        System.out.println("Value of switch is " + switchObject.isSelected() + ", " + text + ", " + switchIsOn);
        if (result == value) {
            System.out.println("Switch set to correct value " + result);
            break;
        } else {
            switchObject.click();
        }
    }
}

private UiObject getSwitchObject() {
    UiObject switchObject = new UiObject(new UiSelector().className(android.widget.Switch.class.getName()));
    assertTrue("Unable to find the switch object", switchObject.exists());
    String text;
    return switchObject;
}

The loop was to compensate for some behaviour I observed, where the click didn't seem to change the switch position.

JulianHarty
  • 3,178
  • 3
  • 32
  • 46
  • what will happen if there are more than one switch elements ? – Rilwan Oct 22 '13 at 06:30
  • @Rilwan can you provide an example in Android where there are multiple switch elements for an item please? And if so, you'd be welcome to post a new question on StackOverflow and link to it from this one. – JulianHarty Oct 30 '13 at 17:41
  • Here in case of Wi-Fi above code will work. But If you look NFC in samsung phones, If you click NFC and goto NFC page--> Again you can see two switches. So if we modify code more generic like this `UiObject item = itemsList.getChildByText(new UiSelector(). className(LinearLayout.class.getName()),switch_label, true); UiObject switchObject = item.getChild(new UiSelector(). className(android.widget.Switch.class.getName()));` Does this make sense ? – Rilwan Oct 31 '13 at 09:09
  • I don't have a suitable Samsung phone to hand & my Nexus 4 only has one tick box to enable or disable NFC so it's not easy for me to check whether your suggested code works, at least currently. Have you tried your code on one of Samsung devices you mention have these 2 switches? – JulianHarty Nov 07 '13 at 00:04
  • Wow... Clicking 5 times on a button (and without sleep) and this is considered as the best answer ?? Someone to explain why it looks so hacky? – Kikiwa Apr 25 '16 at 15:52
  • @kikiwa I agree my solution was ugly and hacky. I wrote it as a proof-of-concept quickly to show that what was asked for *is* doable. It wasn't and isn't intended to be production quality code. You and others are welcome to improve the code and/or provide another, better, answer. All the best. – JulianHarty May 04 '16 at 12:01
  • Thanks @JulianHarty for the response years after. In fact I don't understand why we need this retry loop. In my project, I don't have this loop and it's working great, maybe because I'm waiting for the view, maybe because we are not working on the same Android version, maybe something else? Have you any clue that could explain the need to retry? – Kikiwa May 12 '16 at 13:34
  • 1
    @Kikiwa I wrote the loop at the time, which is early history from an Android perspective, when UI Automator was a juvenile and had several known flaws. I hope these flaws have been addressed in more recent updates to the Android tools, and perhaps the loop isn't needed when using them. I'll leave it here in my answer for 2 main reasons: 1) it's what was needed at the time and some people may still end up using the older releases of the tools & therefore need it 2) it provides an example of an albeit ugly workaround. I've spent this week having to find workarounds for Android Instrumentation! – JulianHarty May 13 '16 at 09:41
  • What is **appViews**? That is not an UiAutomator api. – IgorGanapolsky Mar 15 '17 at 22:21
  • 1
    @IgorGanapolsky Good question, It would have been in the original code I wrote back in 2013. That's probably long lost, or at least would take a while for me to find. I've checked the reference to the Google Docs for clues but they've changed significantly, to the point that I didn't find the example I'd used at the time. I'll take a look and see if I can find the code and/or reproduce this example. If & when I have an update I'll provide it here. – JulianHarty Mar 20 '17 at 23:06
7

To enable WiFi:
device.executeShellCommand("svc wifi enable");

To disable WiFi:
device.executeShellCommand("svc wifi disable");

These are the commands to use on your UiDevice.

avz
  • 71
  • 1
  • 2
2

Used on production on Android 4.2 and 4.4

To open the Android Wifi settings in your code:

final Intent intent = new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK);
mContext.startActivity(intent);

To click the on/off switch with UiAutomator (after you're sure you're on the good activity):

public void enableWifiOnAndroidWifiSettings(boolean enabled) throws UiObjectNotFoundException {
    final UiSelector wifiSwitchSelector = new UiSelector().className(android.widget.Switch.class.getName());
    UiObject wifiSwitch = UiDevice.getInstance(sInstrumentation).findObject(wifiSwitchSelector);
    if (wifiSwitch.waitForExists(5000) && wifiSwitch.isEnabled()) {
        if (wifiSwitch.isChecked() != enabled) {
            wifiSwitch.click();
        }
    }
}

Known limitation: It's searching the first Switch available. If you've custom ROM or if the Android Settings app evolves in the future, it will maybe not be enough.

Kikiwa
  • 1,213
  • 2
  • 13
  • 20
1

In my suite tests with UIAutomator I use:

Runtime.getRuntime().exec("\"svc wifi disable\"")

Runtime.getRuntime().exec("\"svc wifi enable\"")

Runtime.getRuntime().exec("\"svc data disable\"")

Runtime.getRuntime().exec("\"svc data enable\"")
Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107
0

You can enable or disable wifi through adb as follows

adb shell sqlite3 /data/data/com.android.providers.settings/databases/settings.db update secure set value=1 where name='wifi_on'; .exit

But you cannot use uiautomator tool to do the same

Durairaj Packirisamy
  • 4,635
  • 1
  • 21
  • 27
-5

You can't do this. A UI Automator test doesn't run as part of the Android framework, so it has no access to Android system services. It's meant to test UIs; it doesn't claim to be a full-featured test framework. Turn on WiFi manually before you run the test.

Joe Malin
  • 8,621
  • 1
  • 23
  • 18
  • Also i want to know if we can check whether wifi connection is active while running test case in uiautomator, even though i switch on the wifi manually can i check if data packets are exchanged. Is that possible? – user1907534 Dec 22 '12 at 04:49
  • Since we can use all assert functions of android in this, why not this function? – user1907534 Dec 22 '12 at 04:53