I want to send notifications to my phone with php.
I have stored the register id in a database when the user (in this case: me) connects like this in Android:
nvp.add(new BasicNameValuePair("regid", GoogleCloudMessaging.getInstance(c).register(SENDER_ID)));
if (nvp != null) {
httpPost.setEntity(new UrlEncodedFormEntity(nvp));
}
where nvp is a List<NameValuePair>
and SENDER_ID
my project identifier on Google
Then I have a script in Php "sendnotifs.php" like this:
<html>
<head>
<title>GCM Demo application</title>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$connexion = mysqli_connect("localhost:3306", "root", "password", "alo") or die(mysqli_error());
if(!$connexion){die('MySQL connection failed');}
$regid = "
";
echo $regid;
$sql = "SELECT regid FROM personne WHERE id=27";
$result = mysqli_query($connexion,$sql);
$regid = array();
while($row = mysqli_fetch_array($result)){
array_push($regid, $row['regid']);
}
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$message = array("Notice" => $_POST['message']);
$fields = array(
'registration_ids' => $regid,
'data' => $message,
);
$headers = array(
'Authorization: key=Mykey',
'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);
echo $result;
}
?>
<form method="post" action="sendnotifs.php">
<label>Insert Message: </label><input type="text" name="message" />
<input type="submit" name="submit" value="Send" />
</form>
</body>
</html>
where $regid
is the register id end id=27
is my identifier
I have registered my phone by downloading AL-GMC Client and clicking "Register Device for GCM"
And I've wroten class to receive the notifications
public class Objet_GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
Objet_GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
And this one:
public class Objet_GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private static final String TAG = "GcmIntentService";
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public Objet_GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
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(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification(extras.getString("Notice"));
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
Objet_GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Activite_AssistantLevel0.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
// .setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCMDemo")
.setSmallIcon(R.mipmap.logo)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
But it doesn't work...
Where I try to send "I am a fool" on my "sendnotifs.php" page with Google Chrome,I have this kind of return, without notification on my phone...:
{"multicast_id":5009376049877517345,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1440530144017191%e7498dd9f9fd7ecd"}]}
or this one without notifications neither...:
{"multicast_id":7798455372304463190,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}
Does someone know what I've missed? Thanks for your future answers ;)