不使用JSON的GCM推送通知

时间:2012-07-20 09:54:35

标签: android android-c2dm google-cloud-messaging

我正在尝试将我的应用程序从C2DM服务迁移到新的GCM推送通知。我已经成功集成了扩展GCMBaseIntentService的GCMIntentService类。当我使用PHP从服务器发送推送通知时,GCM将消息数据作为JSON对象发送。我在Android GCM服务中使用以下代码,并使用新代码返回null值。

public void onMessage(Context context, Intent intent)
    {
        String action = intent.getAction();     
        if ("com.google.android.c2dm.intent.RECEIVE".equals(action))   {            
             message=intent.getStringExtra("message");                                  
            createNotification(context);
        }
   }

PHP脚本包含:

$ headers = array(                     '授权:key ='。 $ apiKey,                     '内容类型:application / json'                 );

// Open connection
$ch = curl_init();

// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );

curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

请建议我在PHP脚本中使用GCM库和没有JSON发送推送通知的所有更改。

提前致谢 添

2 个答案:

答案 0 :(得分:0)

你必须通过JSON发送有效负载 - 你不想使用JSON的原因是什么?

答案 1 :(得分:0)

您确实可以在没有JSON的情况下发送有效负载(如果您愿意),就像C2DM一样。

首先,内容类型更改为:

Content-Type: application/x-www-form-urlencoded;charset=UTF-8

然后您的HTTP正文将包含此内容:

registration_id=xxxxxx&collapse_key=yyyyy&data.data1=value1&data.data2=value2

但是,通过将有效负载作为纯文本发送,您只能将其发送到one device at a time。仅此原因可以避免使用此选项,除非您的C2DM代码中已经有不希望更改的批量发送逻辑。

请点击此处了解详情:http://developer.android.com/guide/google/gcm/gcm.html#request