[英]Android Studio + Gradle to create different configurations
I am using Android Studio and Gradle to build Android applications. 我正在使用Android Studio和Gradle来构建Android应用程序。 I would like to have different strings within the Java code based on which type of build it is (debug vs. release).
我想在Java代码中有不同的字符串,基于它的构建类型(调试与发布)。 What is the best way to do this?
做这个的最好方式是什么?
For example - I want to have different URLs if I am in debug or release. 例如 - 如果我在调试或发布中,我希望有不同的URL。 Also, I want to specify different GUIDs and other keys / strings.
另外,我想指定不同的GUID和其他键/字符串。
The obvious hacky way to do this is to do a search and replace of a string in AndroidManifest.xml or worse yet, in a Java file. 显而易见的hacky方法是在AndroidManifest.xml中搜索和替换字符串,或者更糟糕的是,在Java文件中。 This approach seems error prone and hacky to me - is there a better way to do this?
这种方法对我来说似乎容易出错并且很容易 - 有没有更好的方法呢?
There are many ways you can do this, although I usually do 虽然我通常会这样做,但有很多方法可以做到这一点
android {
buildTypes {
release {
buildConfigField("String", "URL", "your_url_on_release")
}
debug {
buildConfigField("String", "URL", "your_url_on_debug")
}
}
}
You then can access them on your java code by using: 然后,您可以使用以下命令在Java代码上访问它们:
BuildConfig.URL
You can test this using Android Studio Build Variants, by changing your application variant to debug or release ( eg http://prntscr.com/8waxkw ) 您可以使用Android Studio Build Variants对此进行测试,方法是将应用程序变体更改为调试版或发布版(例如http://prntscr.com/8waxkw )
You have many solutions to do this, here's a simple case: 你有很多解决方案可以做到这一点,这是一个简单的案例:
buildTypes {
debug { ... }
release { ... }
}
productFlavors {
staging { ... }
production { ... }
}
If you want to add resources related to the flavours you can create and add to src/(flavor_name)/res/values/ folder your urls.xml config file. 如果要添加与可以创建的flavor相关的资源,并将urls.xml配置文件添加到src /(flavor_name)/ res / values /文件夹。
With this, in android studio, you'll directly see, all the builds variants in the corresponding window and the right urls.xml file associated to the current context and leave the gradle config clean. 有了这个,在android studio中,您将直接看到相应窗口中的所有构建变体以及与当前上下文关联的正确urls.xml文件,并使gradle配置保持干净。
Of course, this method works also for any resource you would need in your app. 当然,此方法也适用于您在应用中需要的任何资源。
For more detail, you can read this : http://developer.android.com/tools/building/configuring-gradle.html#workBuildVariants 有关更多详细信息,请参阅: http : //developer.android.com/tools/building/configuring-gradle.html#workBuildVariants
在这个解释我将与产品的口味做后期 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.