Android - 如何获得Flavor的ApplicationId

CBA*_*110 13 android gradle android-productflavors

我正在构建一个具有不同构建变体风格的应用程序.口味是"免费"和"付费".我想在我的java类上创建一些逻辑,只有在应用程序为"付费"时才会触发.因此,我需要一种方法来在gradle构建过程中设置"applicationId",如下所示:

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"
    }
Run Code Online (Sandbox Code Playgroud)

一旦我有了应用程序ID,我就可以这样做:

    if(whateverpackageid.equals("paid")) {
      // Do something or trigger some premium functionality.
    } 
Run Code Online (Sandbox Code Playgroud)

我是否正确地说,在gradle构建过程中,"applicationId"最终会在应用程序编译后成为"包名"?如果是这样,获得"应用程序ID"或"包名称"的最佳方法是什么,以便我可以在我的java文件中实现一些与味道相关的逻辑?

小智 24

我会在您的产品风格中使用构建配置变量.有点像:

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"
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在构建之后,您可以使用:

if (BuildConfig.PAID_VERSION) {
    // do paid version only stuff
}
Run Code Online (Sandbox Code Playgroud)

添加属性后,您可能必须在gradle上执行同步/构建,然后才能编译和导入Gradle代表您生成的BuildConfig类.


小智 10

我找到了获得所有值的最佳解决方案,例如APPLICATION_ID,BUILD_TYPE,FLAVOR,VERSION_CODE和VERSION_NAME.

只需写:Log.d("Application Id:",BuildConfig.APPLICATION_ID); 在你的代码中.它将提供您的味道的APPLICATION_ID.

BuildConfig.java

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "";
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此链接:http://blog.brainattica.com/how-to-work-with-flavours-on-android/