I'm trying to write an application to receive notifications via Firebase Cloud Messaging. It initially worked when I tried to send the message via the Firebase console, but then the moment I tried doing the same using PHP webservice, in response, it showed success, but I neither received the message nor am I able to get any more notifications via Firebase console. How can I fix this?
My code in the server side:
<?php
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = AIzaSyDjrLKZGs4OcIgBPxpFnTzGeZHur4v9V8U',
'Content-Type: application/json'
);
$ch = curl_init();
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_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect("localhost:3306", "minaaaa", "tt#2018", "dbSurvey");
$sql = "Select Token From users";
$result = mysqli_query($conn,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["Token"];
}
}
mysqli_close($conn);
$message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
Code in Swift:
UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Util.copyFile(fileName: "db.zanjanwireFinal01.db")
//let alert = UIAlertController(title: title, message: message , preferredStyle: .alert)
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]){(isGranted, err)
in
if err != nil {
}
else
{
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
if let token = InstanceID.instanceID().token() {
print("DCS: " + token)
self.RegisterUsers(testStr: token)
}
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
FirebaseApp.configure()
return true
}
func ConnectToFCM() {
Messaging.messaging().shouldEstablishDirectChannel = true
if let token = InstanceID.instanceID().token() {
print("DCS: " + token)
RegisterUsers(testStr: token)
}
}
func RegisterUsers(testStr:String){
let request = NSMutableURLRequest(url: NSURL(string:
request.httpMethod = "POST"
var dataString = "Token=\(testStr)"
print (dataString)
request.httpBody = dataString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("fffffffffatemeeeeeee")
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
}
task.resume()
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to
// inactive state. This can occur for certain types of
// temporary interruptions (such as an incoming phone call
// or SMS message) or when the user quits the application
// and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers,
// and invalidate graphics rendering callbacks. Games
// should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user
// data, invalidate timers, and store enough application
// state information to restore your application to its
// current state in case it is terminated later.
// If your application supports background execution, this
// method is called instead of applicationWillTerminate:
// when the user quits.
//FirstMenueViewController().update()
Messaging.messaging().shouldEstablishDirectChannel = false
}
func applicationWillEnterForeground(_ application: UIApplication) {
FirstMenueViewController().update()
// Called as part of the transition from the background
// to the active state; here you can undo many of the
// changes made on entering the background.
ConnectToFCM()
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started)
// while the application was inactive. If the application
// was previously in the background, optionally refresh
// the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate.
// Save data if appropriate. See also
// applicationDidEnterBackground:.
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
ConnectToFCM()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
UIApplication.shared.applicationIconBadgeNumber += 1
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "com.DouglasDevlops.BadgeWasUpdated"), object: nil)
}
Structure your notification payload like this,
Related
I am getting the following error when trying to send a Push Notification using Google Firebase:
{"multicast_id":1559489545169770337,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
Can anyone give any clues why please?
It is a new setup and not being imported from GMC.
manifest.json contains:
"gcm_sender_id": "1225****"
This matches "Project Settings" > "Cloud Messaging" > [Sender ID]
The code for registering the user is:
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function subscribePush() {
navigator.serviceWorker.ready.then(function(registration) {
if (!registration.pushManager) {
alert('Your browser doesn\'t support push notification.');
return false;
}
registration.pushManager.subscribe({
userVisibleOnly: true //Set user to see every notification
, applicationServerKey: urlBase64ToUint8Array('*******')
//The "PUBLIC KEY PAIR" under Web configuration. Have tried with and without urlBase64ToUint8Array()
})
.then(function (subscription) {
console.info('Push notification subscribed.');
console.log(subscription);
//saveSubscriptionID(subscription);
})
.catch(function (error) {
console.error('Push notification subscription error: ', error);
});
})
}
My code is registering the user and the response from Firebase is (including "REGISTRATION ID"):
Data {"endpoint":"https://fcm.googleapis.com/fcm/send/****:*****","expirationTime":null,"keys":{"p256dh":"****","auth":"****"}}
I am then using this PHP cURL:
$id = "****:*****"; // "REGISTRATION ID" from the response above. If this is wrong it throws an error ("InvalidRegistration"), so I know that this is correct.
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'registration_ids' => array (
$id
),
'data' => array (
"message" => "Test"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "********", //This is the "Server key" above "Sender ID"
//This matches "Project Settings" > "Cloud Messaging" > [Server Key]
//If this is wrong it returns: INVALID_KEY error 401. So I know this is correct.
'Content-Type: application/json'
);
$ch = curl_init ();
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, $fields );
$result = curl_exec ( $ch );
echo $result;
curl_close ( $ch );
So I eventually figured this out. Instead of using the Subscription ID from the end of
https://fcm.googleapis.com/fcm/send/ABCDEF:KJHASKHDASDetc
I used the following code, and used the TOKEN instead and used that as the "registration_ids" in the CURL post
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-messaging.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "****",
authDomain: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****",
measurementId: "****"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
return messaging.getToken()
})
.then(function(result) {
console.log("The token is: ", result);
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
messaging.getToken({ vapidKey: '*****-*****' }).then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
// ...
console.log("currentToken: ", currentToken);
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
I can succesfully recive notifications from Firebase console, but when I call the PHP function to do it, doesn't recive anything. As I saw on internet, this is more less how I can send these notifications. And what I don't understand what is different when I switch to Firebase console (because it works from there). I don't think the problem is from my app, because I send a request to their server and then they should send to my device. It is very possible to make a mistake, please don't be too rude. I am still a beginner. Thank you for your wise answers!
PHP function
function push_notification_android($device_id,$message){
//API URL of FCM
$url = 'https://fcm.googleapis.com/fcm/send';
$api_key = 'MY_KEY';
$fields = array (
'to' => $device_id,
'data' => array(
"message" => $message,
"id" => '1',
),
);
//header includes Content type and api key
$headers = array(
'Content-Type:application/json',
'Authorization: key='.$api_key
);
$ch = curl_init();
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_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
return $result;
}
{"multicast_id":7370520341381062896,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1611404485967655%6b34551f6b34551f"}]}
By documentation you can send two types of messages to clients:
Notification messages - handled by the FCM SDK automatically.
Data messages - handled by the client app.
If you want to send data message implement your FirebaseMessagingService like this (this is only example what to do, you can use it but improve it with your needs and also test all possible solution to understand how that works)
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
handleDataMessage(remoteMessage.getData());
}else if (remoteMessage.getNotification() != null) {
//remove this line if you dont need or improve...
sendNotification(100, remoteMessage.getNotification().getBody());
}
}
private void handleDataMessage(Map<String, String> data) {
if(data.containsKey("id") && data.containsKey("message")){
String message = data.get("message");
int id;
try {
id = Integer.parseInt(data.get("id"));
}catch (Exception e){
e.printStackTrace();
id = 1; // default id or something else for wrong id from server
}
sendNotification(id, message);
}
}
private void sendNotification(int id, String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "appChannelId"; //getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.icon) //TODO set your icon
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.iconpro_round)) //TODO set your icon
.setContentTitle("MyApp")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) notificationBuilder.setPriority(NotificationManager.IMPORTANCE_HIGH);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(id, notificationBuilder.build());
}
}
}
#adnandann's answer explains the reason indeed: you're sending a data message, while the Firebase console always sends a notification message (which is automatically displayed by the operation system).
So you have two options:
Display the data message yourself, which #adnandann's answer shows how to do.
Send a notification message from your PHP code, which you can do with:
$fields = array (
'to' => $device_id,
'notification' => array(
"title" => "New message from app",
"body" => $message
),
);
I'm currently implement firebase cloud messaging to receive notification from mysql database when a condition in table row data is met. What i currently have right now is just a simple push notification when i enter a php file using browser. Below is all my coding.
push_notification.php
<?php
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = AAAA0********* ',
'Content-Type: application/json'
);
$ch = curl_init();
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_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect("localhost", "root", "", "fcm");
$sql = " Select fcm_token From fcm_notification";
$result = mysqli_query($conn, $sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["fcm_token"];
}
}
mysqli_close($conn);
$message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
registerToken(token);
}
private void registerToken(String token) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("fcm_token", token)
.build();
Request request = new Request.Builder()
.url("http://192.168.1.5/fcm/register.php")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
showNotification(remoteMessage.getData().get("message"));
}
private void showNotification(String message) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("FCM Test")
.setContentText(message)
.setLights(Color.BLUE,1,1)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
}
fcm_token table
token
Right now how do i able to receive a notification from mysql database when a user balance is less than 0.5 and this is my user table
user table
You have set up your system good enough to do the basic thing of sending and receiving the Push Notification.
From what I get is, you are having a system where you want to send a push notification when the user balance is less than 0.5. You can write code in PHP where there is balance manipulation to check user's current balance and send the Push Notification.
OR
You can set up a cron to check balance of each user and send them notification if there balance is less than 0.5
I am working for a few days on an app which is based on real time communication between devices. In the past I was using GCM for notifications via POST methods using the OkHttp library. So far, so good.
But when it comes to real time communication I face a lot of issues around connection timeouts or even mesages which are never delivered.
My implementation is simple. First the user from his phone sends a request via POST and my online server to another phone (driver) which than confirms the request and replies back to the sender via another POST method and via the online server.
But only about 80% of the replies get back to the user, or they arrive after several minutes.
Can the problem be in my implementation?? Or should I switch to GCM Cloud Connection Server (XMPP)??
I am in serious need of some suggestions, please light me up.
Regards.
Php implementation:
<?php
include_once '../includes/db_connect.php';
// Query database for driver's regId
if(!empty($_POST["str"])) {
$sql = "SELECT * FROM DRIVERS WHERE NAME = '$_POST[driver]' " ;
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($result);
$gcmRegID = $row["REGID"];
$clientId = $_POST["clientId"];
$street = $_POST["str"];
$number = $_POST["nr"];
$bloc = $_POST["bl"];
$scara = $_POST["sc"];
if (isset($gcmRegID)) {
$gcmRegIds = array($gcmRegID);
$message = array("jstr" => $street, "jnr" => $number, "jbl" => $bloc, "jsc" => $scara, "jId" => $clientId);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
// Reply to the client if available or not
if(!empty($_POST["response"])) {
$gcmRegID = $_POST["clientId"];
$response = $_POST["response"];
$gcmRegIds = array($gcmRegID);
$message = array("jresp" => $response);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message
);
// Google Cloud Messaging GCM API Key
define("GOOGLE_API_KEY", "**************");
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
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_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
Order Activity - for sending request to the driver
public void callDriver (View view){
MySendTask send = new MySendTask();
send.execute();
Toast.makeText(getApplicationContext(), "Button Pressed :)",
Toast.LENGTH_SHORT).show();
}
private class MySendTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
progressb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String str = streetName.getText().toString();
String nr = streetNr.getText().toString();
String bl = bloc.getText().toString();
String sc = scara.getText().toString();
SharedPreferences prefs = getSharedPreferences("Notification", MODE_PRIVATE);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
try {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(10000, TimeUnit.MILLISECONDS);
RequestBody formBody = new FormEncodingBuilder()
.add("clientId", registrationId)
.add("driver", "Peter Bleul")
.add("str", str)
.add("nr", nr)
.add("bl", bl)
.add("sc", sc)
.build();
Request request = new Request.Builder()
.url("http://edmon.net/andr/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), "Order successfully sent!",
Toast.LENGTH_SHORT).show();
progressb.setVisibility(View.INVISIBLE);
}
}
}
GCM does not guarantee message delivery. GCM also throttles message delivery which can often result in significant delays. For more details on this topic see: http://developer.android.com/google/gcm/adv.html (goto the "Lifetime of a Message" section").
I have experienced issues similar to yours in the app I work on.
Thus it does not seem that GCM is a good candidate for real-time communication.
I have found an excellent example, with great sample applications explaining the process wonderfully, thanks to: Antoine Cambell
I reccomend it for everyone seaking answers for a simmilar application.
I am trying to implement Google Cloud Messaging in my app. Still i can't figure out why i don't get the correct message to my phone. My server sends a message, GCM servers respond to to that and send a message back to my phone.This message looks like this
{\"multicast_id\":8186678237008516542,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1356727074650189%12aaaeccf9fd7ecd\"}]}"
I think that means that i get a message, the problem is my app only shows null value. I am using the Browser Api key right now and get these results, but I have tried to use server key(which theoretically is more suitable to my needs), but i get Error 401.
For receiving the message, i use a broadcast receiver
public void onReceive(Context context, Intent intent){
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);}
EXTRA_MESSAGE = message
This is the code i use in my server.
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_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));
Does anybody know what the problem might be??
I think your response string name mismatch, So please check your response string name. I have used it as "price" in my server side code and in my android side code.you can see it in below images.
File at server side : send_message.php
File at application side : GCMNotificationIntentService
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCMNotificationIntentService";
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
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());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
sendNotification("Message Received from Google GCM Server: "
+ extras.get("price"));
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
//Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.gcm_cloud)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
//Log.d(TAG, "Notification sent successfully.");
}
adjust your code from
'data' => $message,
to be something like this:
'&data.message=' => $message,
and your onMessage() method in GCMIntentService should be something like below:
protected void onMessage(Context ctx, Intent intent) {
// TODO Auto-generated method stub
String message =intent.getStringExtra("message");;
}