PubNub + GCM推送通知与常规PubNub消息

时间:2016-02-03 08:12:03

标签: android google-cloud-messaging pubnub

我正在寻找有效使用PubNub和GCM的一些说明。我已根据this PubNub guide中的说明设置了我的应用,并且它正在100%工作。但是我现在需要将自己的代码插入到这个东西中,我想知道是否有一个明确的方法来实现我想要的东西。

  • 如果应用程序位于前台,则正常接收消息并正常更新UI。但是当应用程序在后台时,请在pendingIntent中发送带有消息有效负载的GCM推送作为额外内容。请理解我不会询问如何检测应用程序是否在后台/前台。

我现在的想法是完全依靠GCM推送来携带我的有效载荷数据,因为发送它两次是多余的。然后只会调用订阅来加入他们将接收推送的频道。接收器的onReceive将检查isAppInBackground,如果是,则调用sendNotification。这样做有问题吗?

目前通过PubNub向频道发送信息的方式如下:

 private void sendThatJSONInfo(String channelID){
    JSONObject jason = new JSONObject();

    try {

        jason.put("data1", aString);
        jason.put("data2", anotherString);
        jason.put("fromWho", username);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    pN.publish(channelID, jason, new Callback() {
    });
}

要将GCM 发送到同一频道,我的代码是这样的:

 public void sendNotification(View view) {
    PnGcmMessage gcmMessage = new PnGcmMessage();
    JSONObject jso = new JSONObject();
    try {
        jso.put("data1", aString);
        jso.put("data2", anotherString);
        jso.put("fromWho", username);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    gcmMessage.setData(jso);

    PnMessage message = new PnMessage(
            pubnub,
            CHANNEL,
            callback,
            gcmMessage);
    try {
        message.publish();
    } catch (PubnubException e) {
        e.printStackTrace();
    }
}

我希望我的问题很明确。我已经浓缩并重复了下面的内容:

  • 是否可以将这两种方法结合使用,以便在应用处于后台时接收推送?我有一些想法,但我想知道是否已经有一个最好的做法,或者至少我可以前往的方向。

1 个答案:

答案 0 :(得分:0)

使用PubNub Android SDK发送GCM推送通知

您可以创建PnGcmMessage并将其添加到您发布的PnMessage。我更喜欢使用原始JSObject并在没有辅助方法的情况下自己创建所有内容,但这种技术对您来说更容易。另外,请阅读Publishing to GCM with Java docs‌

您可以选择忽略发送推送消息的特殊方法,而忽略add pn_gcm content to the message payload in the publish

此示例Sending and Receiving Android Push Notifications w/ GCM应提供您需要的详细信息。