gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:20:09 24 4
gpt4 key购买 nike

我对 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

}

}


}

最佳答案

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

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

关于php - GCM 向多个客户端发送多条消息(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20832064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com