问题
I am trying to migrate my application from C2DM service to new GCM push notification. I have successfully integrated the GCMIntentService class which extends GCMBaseIntentService. When I send the push notification from server using PHP, the GCM sends the message data as a JSON object. I am using the following code in my Android GCM service, and its returning a null value with the new code.
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);
}
}
The PHP Script contains :
$headers = array( 'Authorization: key=' . $apiKey, 'Content-Type: 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 ) );
Please suggest me what all the changes I require in my PHP script to send the push notification using GCM libraries and without JSON.
Thanks in advance Tim
回答1:
you have to send the payload via JSON - whats the reason you do not want to use JSON?
回答2:
You can indeed send payload without JSON (if you preferred), just like C2DM.
First, the content type is changed to this:
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Then your HTTP body will contain this:
registration_id=xxxxxx&collapse_key=yyyyy&data.data1=value1&data.data2=value2
HOWEVER, by sending payload as plain text you can only send it to one device at a time
. This reason alone should make you avoid using this option, unless you already have bulk-sending logic in your C2DM code that you don't wish to change.
See here for more details: http://developer.android.com/guide/google/gcm/gcm.html#request
来源:https://stackoverflow.com/questions/11577033/gcm-push-notification-without-using-json