GCM向多个客户端发送多条消息(阵列)

时间:2013-12-30 01:20:57

标签: php android arrays push-notification google-cloud-messaging

我对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 个答案:

答案 0 :(得分:2)

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

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