5

我正在编写一个与SmoochCarnival集成的应用程序。这两个库都使用定义 GCM Intent 服务以接收消息的标准方法接收 GCM 推送消息。

当我只使用 Smooch 时,一切都很好。当我只使用嘉年华时,一切都很好。当我尝试同时使用两者时,问题就出现了。我发现 GCM 接收器将简单地启动清单中列出的第一个定义 intent 的服务com.google.android.c2dm.intent.RECEIVE

事实上,我发现库在我的build.gradle影响中列出的顺序是它们的清单合并到应用程序清单中的顺序。所以,如果我把 smooch 放在首位,它会起作用(但 Carnival 没有收到任何东西)。如果我把嘉年华放在首位,它会起作用(但 Smooch 从来没有收到任何东西)。

当我不控制任何一个时,如何处理多个 GCM 意图服务?一般来说,应用程序应该如何定义和管理多个 GCM Intent 服务?

4

2 回答 2

6

您无法在 Carnival 和 Smooch 中工作的原因是这两个库都在注册自己的 GcmListenerService,并且在 Android 中,清单中定义的第一个 GcmListenerService 将接收所有 GCM 消息。

我有一个主要基于以下 SO 文章的解决方案: Multiple GCM listeners using GcmListenerService

最好的解决方案是只有一个 GcmListenerService 实现,并为两者处理消息。

要指定您自己的 GcmListenerService,请按照Google 云消息传递文档中的说明进行操作。

当您拥有自己的 GCM 注册时,Smooch 为您提供了禁用其内部 GCM 注册所需的工具。

为此,只需setGoogleCloudMessagingAutoRegistrationEnabled在初始化 Smooch 时调用:

Settings settings = new Settings("<your_app_token>");
settings.setGoogleCloudMessagingAutoRegistrationEnabled(false);
Smooch.init(this, settings);

并在你自己的,用你的令牌GcmRegistrationIntentService打电话。Smooch.setGoogleCloudMessagingToken(token);

完成后,您就可以将 GCM 消息传递给您想要的任何 GCM 接收器。

@Override
public void onMessageReceived(String from, Bundle data) {
    final String smoochNotification = data.getString("smoochNotification");

    if (smoochNotification != null && smoochNotification.equals("true")) {
        data.putString("from", from);

        Intent intent = new Intent();
        intent.putExtras(data);
        intent.setAction("com.google.android.c2dm.intent.RECEIVE");
        intent.setComponent(new ComponentName(getPackageName(), "io.smooch.core.GcmService"));

        GcmReceiver.startWakefulService(getApplicationContext(), intent);
    }
}

编辑

从 Smooch 版本 3.2.0 开始,您现在可以通过调用GcmService.triggerSmoochGcmonMessageReceived 更轻松地触发 Smooch 的通知。

@Override
public void onMessageReceived(String from, Bundle data) {
    final String smoochNotification = data.getString("smoochNotification");

    if (smoochNotification != null && smoochNotification.equals("true")) {
        GcmService.triggerSmoochGcm(data, this);
    }
}
于 2016-04-11T14:12:25.363 回答
0

您将两者都用作 gradle 依赖项?您必须下载这两个库并将它们用作模块,它们可能使用相同的服务,如果您下载它们,您可以更改服务名称并解决可能与两者相关的任何问题。

我的猜测是,您可能必须使用您的应用程序模块创建 GCM 广播接收器(即使它调用 libs 服务)。

于 2016-04-11T00:45:15.777 回答