Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - dynamic configuration in gradle based on build type

I am developing an app for Android that connects to my server. As usual my server during development is on a laptop and its ip is changing. I would like to detect ip address of my development machine i.e.

InetAddress.getLocalHost().getCanonicalHostName()

...and inject it into android strings.xml file so my Android app would connect to right ip during development.

I am struggling with determining where to get info what kind of buildType is run following part can be executed each time:

android { 
    buildTypes.each { buildType ->
        if(buildType.name == 'debug') {
            def host = InetAddress.getLocalHost().getCanonicalHostName()
        }
    }
}

Let's say that that host is determined right now. However I am still not sure how to replace host in strings.xml file in order to connect to the right host. I cannot call processResources as following exception is thrown:

Could not find method processResources() for argument [build_11onjivreh0vsff0acv5skf836$_run_closure3@cbbe2cf] on project

Any suggestion or source code would be appreciated.

like image 418
Bart Avatar asked Dec 02 '22 18:12

Bart


2 Answers

There is an much easier solution available: Use a static final in BuildConfig:

buildTypes {
    debug {
        def host = InetAddress.getLocalHost().getCanonicalHostName()
        buildConfig "public static final String API_HOSTNAME = \"" + host + "\";"
    }

    release {
        buildConfig "public static final String API_HOSTNAME = \"whateveritisforreleasebuilds\";"
    }
}

BuildConfig.API_HOSTNAME will hold the remote address.

like image 196
flx Avatar answered Dec 10 '22 11:12

flx


The following Syntax is required for the latest versions:

buildTypes {
    debug {
        buildConfigField "String", "ENVIRONMENT", "\"development\""
    }
    release {
        buildConfigField "String", "ENVIRONMENT", "\"production\""
    }
}

alternatively with a boolean type:

buildTypes {
    debug {
        buildConfigField "boolean", "ENVIRONMENT", "true"
    }
    release {
        buildConfigField "boolean", "ENVIRONMENT", "false"
    }
}

You would then use this as

BuildConfig.ENVIRONMENT.equals("production"); // String type

or

if (BuildConfig.ENVIRONMENT) { ... } // boolean type
like image 45
14 revs, 12 users 16% Avatar answered Dec 10 '22 11:12

14 revs, 12 users 16%