更新:GCM已弃用,使用FCM

我正在实现新的谷歌云消息,遵循从谷歌开发人员页面这里的指南

我已经成功地运行并测试了它。但我现在的问题是,我有不同的产品口味,具有不同的applicationId/packageName和不同的谷歌云消息传递项目Id。谷歌服务。Json必须放在/app/google-services。Json,而不是flavor文件夹。

有没有办法让谷歌的服务。Json配置不同的许多口味?


当前回答

写了一篇关于这个问题的文章。

有一个类似的问题(使用BuildTypes而不是flavour),并像这样修复了它。

利用Gradle的依赖管理系统。我创建了两个任务switchToDebug和switchToRelease。要求在运行assemblerrelease时,也运行switchToRelease。调试也是一样。

def appModuleRootFolder = '.'
def srcDir = 'src'
def googleServicesJson = 'google-services.json'

task switchToDebug(type: Copy) {
    def buildType = 'debug'
    description = 'Switches to DEBUG google-services.json'
    from "${srcDir}/${buildType}"
    include "$googleServicesJson"
    into "$appModuleRootFolder"
}

task switchToRelease(type: Copy) {
    def buildType = 'release'
    description = 'Switches to RELEASE google-services.json'
    from "${srcDir}/${buildType}/"
    include "$googleServicesJson"
    into "$appModuleRootFolder"
}

afterEvaluate {
    processDebugGoogleServices.dependsOn switchToDebug
    processReleaseGoogleServices.dependsOn switchToRelease
}

编辑:使用processDebugFlavorGoogleServices/processReleaseFlavorGoogleServices任务在每个flavor级别上修改它。

其他回答

我发现google-services插件对于想要添加GCM的项目来说是非常无用的。它只生成以下文件,简单地将您的项目ID添加为字符串资源:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- Your API key would be on the following line -->
    <string name="gcm_defaultSenderId">111111111111</string>
</resources>

似乎只有在直接从Cloud Messaging for Android指南复制样例代码时才需要它。下面是示例行:

String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),              GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

解决方案

如果您希望能够为不同的构建类型或产品风格切换API项目,您只需定义自己的常量,并在调用getToken() API时选择适当的常量。

private static final String SENDER_ID = "111111111111";
private static final String SANDBOX_SENDER_ID = "222222222222";

String token = instanceID.getToken(
        BuildConfig.DEBUG ? SENDER_ID : SANDBOX_SENDER_ID,
        GoogleCloudMessaging.INSTANCE_ID_SCOPE,
        null);

产品口味

上面的代码用于在调试和发布版本之间切换。对于产品类型,您可以在java源文件中定义不同的API键,并将这些文件放在相应的产品类型目录中。参考:Gradle Build variables

我知道,你怀疑谷歌的服务。Json文件应该放在根应用程序文件夹,是吗?我将打破这个神话——不一定。你可以写谷歌服务。Json文件到flavor文件夹中。是这样的:

我目前在同一个应用程序包中使用两个GCM项目Id。我加入了谷歌服务。我的第一个GCM项目的json,但我从第一个切换到第二个只改变SENDER_ID:

    String token = instanceID.getToken(SENDER_ID,GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

(在这一点上,我认为谷歌的服务。Json不是强制性的)

所以如果你想通过编程复制google的服务。Json文件从你的所有变体到你的根文件夹。当你切换到特定的变体时,这里有一个解决方案

android {
  applicationVariants.all { variant ->
    copy {
        println "Switches to $variant google-services.json"
        from "src/$variant"
        include "google-services.json"
        into "."
    }
  }
}

这种方法有一个警告,那就是你需要有谷歌服务。Json文件在你的每个变体文件夹这里是一个例子。

嘿,朋友也寻找名称只使用小写,那么你不会得到这个错误