Android-如何获取Flavor的ApplicationId
我正在构建具有不同构建变体口味的应用程序.口味为免费"和付费".我想在我的java类上创建一些逻辑,这些逻辑仅在应用程序为付费"时才被触发.因此,我需要一种方法来在gradle构建过程中设置"applicationId",如下所示:
I'm building an app wit different build variant flavors. The flavors are "Free" and "Paid". I want to create some logic on my java classes which should only get triggered if the app is "Paid". Therefore I need a way to get the "applicationId" set during the gradle build process as shown below:
gradle.build
productFlavors {
free {
applicationId "com.example.free"
resValue "string", "app_name", "Free App"
versionName "1.0-free"
}
paid {
applicationId "com.example.paid"
resValue "string", "app_name", "Paid App"
versionName "1.0-paid"
}
一旦有了应用程序ID,我就可以执行以下操作:
Once I have the application ID I could do something like this:
if(whateverpackageid.equals("paid")) {
// Do something or trigger some premium functionality.
}
我是否正确地说,在gradle构建过程中,一旦编译了应用程序,"applicationId"最终将成为程序包名称"?如果是这样,什么是获取应用程序ID"或程序包名称"的最佳方法,以便我可以在Java文件中实现一些依赖于口味的逻辑?
Am I correct to say that during the gradle build process the "applicationId" eventually becomes the "package name" once the app has been compiled? If so what is the best way to get either the "application ID" or "package name" so that I can implement some flavor dependent logic in my java files?
我会在您的产品中使用构建配置变量.类似于:
I would use build configuration variables in your product flavors. Something along the lines of:
productFlavors {
free {
applicationId "com.example.free"
resValue "string", "app_name", "Free App"
versionName "1.0-free"
buildConfigField "boolean", "PAID_VERSION", "false"
}
paid {
applicationId "com.example.paid"
resValue "string", "app_name", "Paid App"
versionName "1.0-paid"
buildConfigField "boolean", "PAID_VERSION", "true"
}
}
然后在构建之后,您可以使用:
Then after a build you can use:
if (BuildConfig.PAID_VERSION) {
// do paid version only stuff
}
添加属性后,您可能必须在gradle上进行同步/构建,然后才能编译和导入Gradle代表您生成的BuildConfig类.
You may have to do a sync/build on gradle after you add the attribute before you can compile and import the BuildConfig class that Gradle generates on your behalf.