Android Studio: Switching a URL depending on buildtype? (used for testing in debug /release)

纵然是瞬间 提交于 2019-12-03 04:52:27

问题


I have been reading something about variants and buildtypes and I don't know if I am understanding it right but I would like to store a URL for locahost (testing) and one for production (live site on the internet).

And I need to switch them depending on which buildtype. Is this the right way to do this ? or is there another alternative ?

Does anyone have a small example ?

Is there a way of storing this information in a file that I do not need to commit to source control ? I am using the gradle.properties file for storing some passwords that gradle uses for the signings.. This works great as this file I do not share in version control.

I am a little confused of the correct method to use and how to implement it.

Any ideas?


回答1:


You can use the BuildConfig for supplying different URLs for each BuildType

buildTypes {
    debug {
        buildConfigField "String", "SERVER_URL", '"http://someurl/"'
    }
    release{
        buildConfigField "String", "SERVER_URL", '"http://someotherurl/"'
    }
}   

The BuildConfig will be autogenerated each time you sync your project with the gradle file. In your code, you can access the URL like this:

BuildConfig.SERVER_URL

If you don't want to commit these URLs, you can store them in your gradle.properties just like your password and such and reference them in the build.gradle.

buildConfigField "String", "SERVER_URL", serverurl.debug



回答2:


   buildTypes {
    release {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        buildConfigField "String", "BASE_URL", '"url1"'
        debuggable false

    }

   debug {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        buildConfigField "String", "BASE_URL", '"url2"'
        debuggable true

 }

This you need to do in the gradle and to make run two applications(release and debug) in a same phone just add

applicationIdSuffix ".debug"

in debug portion. As the package name will be different. This worked for me.



来源:https://stackoverflow.com/questions/27875748/android-studio-switching-a-url-depending-on-buildtype-used-for-testing-in-deb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!