Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Studio - get build machine's IP address into Android app

During app development, I want the app to connect back to the machine it was built on (over Wifi).

As we have multiple developers, this will be a different IP address for each developer.

How can I do this?

(Some developers use AndroidStudio on Windows 7, other AndroidStudio on Ubuntu 14.04LTS.)

like image 622
fadedbee Avatar asked Feb 24 '15 10:02

fadedbee


People also ask

How to get the IP address of Android device programmatically?

This example demonstrates how do I get the IP address of android device programmatically. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. Step 3 − Add the following code to src/MainActivity.java. ...

How do I build and run an Android app?

To build and run your app, follow these steps: In the toolbar, select your app from the run configurations drop-down menu. From the target device drop-down menu, select the device that you want to run your app on. If you don't have any devices configured, then you need to either connect a device via USB or create an AVD to use the Android Emulator.

How to create a new project in Android Studio?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml.

How do I create an APK file in Android Studio?

Alternatively, you can select Build > Generate Signed Bundle / APK from the menu bar. Android Studio saves the APKs you build in project-name/module-name/build/outputs/bundle/ . Brings up a dialog with a wizard to set up a new signing configuration, and build either a signed app bundle or APK.


1 Answers

This is my solution. Really useful to keep a clean git status.

/**
 * Find the first LAN address of the development machine.
 */
def getDevHost = { ->
    def defaultDevHost = InetAddress.getLocalHost()
            .getCanonicalHostName()

    return NetworkInterface.getNetworkInterfaces()
            .findResult(defaultDevHost) {
        def ifOk = it.isUp() &&
                !it.isVirtual() &&
                !it.isPointToPoint() &&
                !it.isLoopback() &&
                !it.getName().startsWith("br-") // 

        if (ifOk)
            return it.getInetAddresses().find {
                it instanceof Inet4Address &&
                        !it.isLoopbackAddress()
            }
        else
            return null
    }
}

I'm using it for a single buildType of the project:

android {
  // ...

  buildTypes {
    // ...

    dev {
      // ...
      buildConfigField "String", "BACKEND_URL", "\"http://${getDevHost()}:9000/\""
    }
  }
}
like image 52
László Kustra Avatar answered Sep 28 '22 06:09

László Kustra