首页 文章

在一个应用程序中使用2个或更多GCM Intent服务

提问于
浏览
5

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

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

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

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

2 回答

  • 6

    你不能推在两个嘉年华和接吻工作的原因是这两个库正在注册自己的GcmListenerService,并在Android的在你的清单中定义将接收所有的GCM消息的第一GcmListenerService .

    我主要根据以下SO文章为您提供解决方案:Multiple GCM listeners using GcmListenerService

    最好的解决方案是只有一个GcmListenerService实现,并为它们处理消息 .

    要指定您自己的GcmListenerService,请按照Google's Cloud Messaging Documentation中的说明进行操作 .

    Smooch提供了在您拥有自己的GCM注册时禁用其内部GCM所需的工具 .

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

    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);
        }
    }
    

    EDIT

    从Smooch版本3.2.0开始,您现在可以通过在onMessageReceived中调用GcmService.triggerSmoochGcm来更轻松地触发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);
        }
    }
    
  • 0

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

    我的猜测是你可能不得不用app模块创建GCM广播接收器(即使它调用了libs服务) .

相关问题