How to pass a parameter to the Java code in run/debug configuration from Android Studio

后端 未结 4 1989
北海茫月
北海茫月 2021-02-04 12:47

My android app does some http requests to my server. However sometimes I am debugging the new api code that runs on my development machine. I would like to be able to pass somet

4条回答
  •  遥遥无期
    2021-02-04 13:15

    I know this thread is quite old, but in my opinion none of provided answers actually solves the problem. Flavors are ill-suited for parametrizing your build with things like API URLs, and even worse for things like API keys etc.

    Firstly, build.gradle which defines flavors is part of project source, therefore it must not contain such information in order to be safely committed into source control systems.

    Secondly, a need may arise to test different flavors against different API endpoints/keys. What if you just want to hit some debug http server you just created to solve a bug? Would you create a flavor for that? Probably not... Flavors are good for things like "free flavor" and "premium flavor".

    This problem is easily solved using gradles -P flag. You can access gradle properties that are passed this way as regular variables inside your gradle.build, and you can vary it's behavior accordingly.

    If you want to push this flags further into your application you can use Scott's solution that was posted here, combined with the provided flag.

    The build command would then probably look like:

    $ gradle build -Papiroot=http://www.example.com
    

    And in your build.gradle you would define the writeValue task like this:

    task writeValue(type:Exec) {
        commandLine '/usr/local/bin/adb', 'shell', "echo 'API_SERVER=${apiroot}' > /data/data/values.properties"
    }
    

    FYI the -P flag can be easily configured in Android Studio by navigating from the menu:

    Run -> Run/Debug Configurations -> Defaults -> Gradle -> Script Parameters

提交回复
热议问题