GCM 向多个客户端发送多条消息(数组)

Posted

技术标签:

【中文标题】GCM 向多个客户端发送多条消息(数组)【英文标题】:GCM sending multiple messages (array) to multiple client 【发布时间】:2013-12-30 01:20:57 【问题描述】:

我对 GCM 消息有疑问。如果消息是数组的形式,我不知道如何处理。目前我的代码适用于简单的消息,例如“$message = 1;”

但是我想发送一条包含数据库查询数组的消息。 目前我正在从数据库查询(多个 ID)中获取注册 ID,并且它正在工作,所以大概它对消息的工作方式相同,但到目前为止还没有运气。

下面提供了客户端和服务器(php)端,我需要一种在客户端处理数组消息的方法。任何帮助表示赞赏。

这是 php 服务器部分。这部分工作正常。

<?php
// Message to be sent

function Reg() 

  require_once __DIR__ . '/db_connect.php';

    $db = new DbConnect();
$response = array();
$response1 = array();


$API_Key='AIzaSyCQgPGhpAzuWGuUd0DCI8pYaXXAItthEsg';
$url = 'https://android.googleapis.com/gcm/send';

$result1 = mysql_query("SELECT *FROM test") or die(mysql_error());
$stack = array();

    while ($row = mysql_fetch_array($result1)) 

        $Reg_ID = $row["Reg_ID"];
        $Distance = $row["Distance"];
        array_push($response1, $Distance);

    


$result = mysql_query("SELECT *FROM registrationid") or die(mysql_error());
$stack = array();

    while ($row = mysql_fetch_array($result)) 

        $Reg_ID = $row["Reg_ID"];
        $Registration_ID = $row["Registration_ID"];
        array_push($response, $Registration_ID);

    

$fields = array(
            'registration_ids' => $response,
            'data' => $response1 ,
        );

        print_r ($fields);

        print_r ($response1);

        $headers = array(
            'Authorization: key=' . $API_Key,
            '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);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

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

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) 
            die('Curl failed: ' . curl_error($ch));
        

        // Close connection
        curl_close($ch);

    

    Reg();

?>

这是客户端。

package com.techlovejump.gcm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.EditText;
public class GcmIntentService extends IntentService
    Context context;
    private static String URL_GPS = "http://10.0.2.2/GET_EVERYTHING_TOGTHER/Get_GPS_From_Bus.php";
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    JSONParser jsonParser = new JSONParser();
    public static final String TAG = "GCM Demo";
    GPSTracker gps;

    public GcmIntentService() 
        super("GcmIntentService");
        // TODO Auto-generated constructor stub
    

    @Override
    protected void onHandleIntent(Intent intent) 
        // TODO Auto-generated method stub
        Bundle extras = intent.getExtras();
        String msg = intent.getStringExtra("message");
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String messageType = gcm.getMessageType(intent);

         if (!extras.isEmpty()) 

             if (GoogleCloudMessaging.
                        MESSAGE_TYPE_SEND_ERROR.equals(messageType)) 
                    sendNotification("Send error: " + extras.toString());
                 else if (GoogleCloudMessaging.
                        MESSAGE_TYPE_DELETED.equals(messageType)) 
                    sendNotification("Deleted messages on server: " +
                            extras.toString());
                // If it's a regular GCM message, do some work.
                 else if (GoogleCloudMessaging.
                        MESSAGE_TYPE_MESSAGE.equals(messageType)) 
                    // This loop represents the service doing some work.
                    for (int i=0; i<5; i++) 
                        Log.i(TAG, "Working... " + (i+1)
                                + "/5 @ " + SystemClock.elapsedRealtime());
                        try 
                            Thread.sleep(500);
                         catch (InterruptedException e) 
                        
                    
                    Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                    // Post notification of received message.
                    //sendNotification("Received: " + extras.toString());


                    Log.i("MSG", msg);
                    Log.e("msg", msg);
                    Log.i(TAG, "Received: " + extras.toString());
                    sendNotification(msg);
                    ///////ADDED on 27/12/2013
                    //////////////////////////////////////////////////////add one here 
                    GPS_Configure(msg);
                    //////////////////////////////////////////////////////
                
            
         GcmBroadcastReceiver.completeWakefulIntent(intent);
    
    private void sendNotification(String msg) 
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent myintent = new Intent(this, ReceiveActivity.class);
        myintent.putExtra("message", msg);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                myintent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_stat_gcm)
        .setContentTitle("GCM Notification")
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(msg))
        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    

    private void GPS_Configure(String msg) 
        gps = new GPSTracker(GcmIntentService.this);

        // check if GPS enabled
        if (gps.canGetLocation()) 

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();
            Log.i("latitude", Double.toString(latitude));
            Log.i("longitude", Double.toString(longitude));


            new GPS_GetData().execute(Double.toString(latitude),
                    Double.toString(longitude), msg);

         else 
            gps.showSettingsAlert();
        
    


    class GPS_GetData extends AsyncTask<String, String, String> 

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() 
            super.onPreExecute();

        

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) 

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //params.add(new BasicNameValuePair("latitude", args[0]));
            //params.add(new BasicNameValuePair("longitude", args[1]));
            params.add(new BasicNameValuePair("latitude", "31.97198937240043"));
            params.add(new BasicNameValuePair("longitude", "35.1956698624676"));
            params.add(new BasicNameValuePair("Request_ID", args[2]));
            Log.i("LAT", args[0]);



            // getting JSON Object
            // Note that create product url accepts POST method


                JSONObject json = jsonParser.makeHttpRequest(URL_GPS,
                        "POST", params);



            // check log cat fro response
        //  Log.d("Create Response", json.toString());

            return null;
        

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) 
            // dismiss the dialog once done

        

    



【问题讨论】:

【参考方案1】:

你想要完成的事情是不可能的。 GCM 支持在单个 HTTP 请求中向多个注册 ID 发送相同的消息,但所有注册 ID 的消息负载相同。

如果您需要向每个注册 ID 发送不同的消息负载,则必须分别发送每条消息(在不同的 HTTP 请求中)。

【讨论】:

以上是关于GCM 向多个客户端发送多条消息(数组)的主要内容,如果未能解决你的问题,请参考以下文章

GCM 向多个设备发送消息

GCM使用java发送消息

GCM 多次推送同一消息 (PushSharp)

如何从应用服务器向 GCM 服务器发送发送重新注册请求以注册设备?

GCM 和 WNS 禁止向非活动设备发送推送通知的策略

GCM 客户端收不到下游消息