Tuesday, September 26, 2017

Android - set host IP on app

Android - dynamic host IP

I want to test my Android RESTful API requests against the mock web server running on the same PC. The PC has dynamically assigned IP address, so the mock web server might also have different IP address when I restart the server. I could manually change the server IP on Android source code when new IP is assigned, but it’s not practical because not only do I modify the source code, it will also block the tests on daily build machine. The code snippet is to demonstrate how to dynamically set the host IP address on Android.

Setup

  • Android Studio

Development

build.gradle

android {
    . . .
    buildTypes {
        debug {
            buildConfigField "String", "SERVER_ADDR", '\"' + getHostIp() + '\"'
        }
        release {
            . . .
        }
    }
}

def getHostIp() {
    String result = "127.0.0.1";
    Enumeration ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        if (!iface.isLoopback()) {
            for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) {
                if (ifaceAddr.getAddress().isSiteLocalAddress()) {
                    result = ifaceAddr.getAddress().getHostAddress();
                    break;
                }
            }
        }
    }
    return result;
}

Now the host IP can be obtained from SERVER_ADDR

package com.example;

import static com.example.test.BuildConfig.SERVER_ADDR;

@RunWith(AndroidJUnit4.class)
public class RESTApiTest {
    private final static String MOCK_SERVER = "http://" + SERVER_ADDR + “:5438/API/v1.0/“;

    @Test
    Public void testHelloWorld {
        . . .
    }
}

In case you are running the tests on an actual device, make sure the device is also running on the same subnet.

No comments:

Post a Comment