您无法在 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.triggerSmoochGcm
onMessageReceived 更轻松地触发 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);
}
}