I want to send notification using FCM. I have added project to Firebase Console got the API key and device_token.
Now I am sending a push notification from PHP, I get the message in logs, but it's showing some exception. I have followed this tutorial.
PHP script function:
function sendInvite()
{
$database = new Database(ContactsConstants::DBHOST, ContactsConstants::DBUSER, ContactsConstants::DBPASS, ContactsConstants::DBNAME);
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("select * from Invitation where user_name =? and sender_id = ?");
$stmt->execute(array($this->user_name,$this->sender_id));
$rows = $stmt->rowCount();
if ($rows > 0) {
$response = array("status" => -3, "message" => "Invitation exists.", "user_name" => $this->user_name);
return $response;
}
$this->date = "";
$this->invitee_no = "";
$this->status = "0";
$this->contact_id = 0;
$stmt = $dbConnection->prepare("insert into Invitation(sender_id,date,invitee_no,status,user_name,contact_id) values(?,?,?,?,?,?)");
$stmt->execute(array($this->sender_id, $this->date, $this->invitee_no, $this->status, $this->user_name,$this->contact_id));
$rows = $stmt->rowCount();
$Id = $dbConnection->lastInsertId();
$stmt = $dbConnection->prepare("Select device_id from Users where user_id =?");
$stmt->execute(array($this->sender_id));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$token = $result["device_id"];
$server_key = 'AIzaJaThyLm-PbdYurj-bYQQc';
$fields = array();
$fields['data'] = $data;
if(is_array($token)){
$fields['registration_ids'] = $token;
}else{
$fields['to'] = $token;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$server_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_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('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
echo $result;*/
$message = 'Hi,add me to your unique contact list and you never need to update any changes anymore!';
$data = array("message"=>"Hi,add me to your unique contact list and you never need to update any changes anymore!","title"=>"You got an Invitation.");
if (!empty($token)) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'to' => $token,
'data' => $data
);
$fields = json_encode($fields);
$headers = array(
'Authorization: key=' . "AIzaSyBGwwJaThyLm-PhvgcbdYurj-bYQQ7XmCc",
'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_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
}
$stmt = $dbConnection->prepare("select * from Invitation where invitation_id=?");
$stmt->execute(array($Id));
$invitation = $stmt->fetch(PDO::FETCH_ASSOC);
if ($rows < 1) {
$response = array("status" => -1, "message" => "Failed to send Invitation., unknown reason");
return $response;
} else {
$response = array("status" => 1, "message" => "Invitation sent.", "Invitation:" => $invitation);
return $response;
}
}
MessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
public static final String PUSH_NOTIFICATION = "pushNotification";
private NotificationUtils notificationUtils;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
private void handleNotification(String message) {
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
}else{
// If the app is in background, firebase itself handles the notification
}
}
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "push json: " + json.toString());
try {
JSONObject data = json.getJSONObject("data");
String title = data.getString("title");
String message = data.getString("message");
// boolean isBackground = data.getBoolean("is_background");
String imageUrl = data.getString("image");
String timestamp = data.getString("timestamp");
// JSONObject payload = data.getJSONObject("payload");
Log.e(TAG, "title: " + title);
Log.e(TAG, "message: " + message);
// Log.e(TAG, "isBackground: " + isBackground);
// Log.e(TAG, "payload: " + payload.toString());
Log.e(TAG, "imageUrl: " + imageUrl);
Log.e(TAG, "timestamp: " + timestamp);
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent(PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", message);
// check for image attachment
if (TextUtils.isEmpty(imageUrl)) {
showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
} else {
// image is present, show notification with image
showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
}
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
/**
* Showing notification with text and image
*/
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}
}
Exception:
E/MyFirebaseMessagingService: From: 321839166342
10-12 11:49:14.744 21621-27002/com.example.siddhi.contactsapp E/MyFirebaseMessagingService: Data Payload: {title=You got an Invitation., message=Hi,add me to your unique contact list and you never need to update any changes anymore!}
10-12 11:49:14.745 21621-27002/com.example.siddhi.contactsapp E/MyFirebaseMessagingService: Exception: Unterminated object at character 12 of {title=You got an Invitation., message=Hi,add me to your unique contact list and you never need to update any changes anymore!}
What's going wrong here?
I also want to make notification responsive. As it should have Accept and Reject option and on click of that, I want to perform an action.
Can anyone help with this please? Thank you..
Try with below example with manually device token pass
<?php
define("ANDROID_PUSHNOTIFICATION_API_KEY",'API_KEY_HERE'); // FCM
define("ANDROID_PUSHNOTIFICATION_URL",'https://fcm.googleapis.com/fcm/send'); // FCM
function push_android($devicetoken,$param){
$apiKey = ANDROID_PUSHNOTIFICATION_API_KEY; //demo
$registrationIDs[] = $devicetoken;
// Set POST variables
$url = ANDROID_PUSHNOTIFICATION_URL;
$fields = array(
'registration_ids' => $registrationIDs,
'data' => $param,
);
$headers = array(
'Au
thorization: key=' . $apiKey,
'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 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
//print_r($result); exit;
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}else{
//echo "success notification";
//print_r($result);
//echo curl_error($ch);
}
// Close connection
curl_close($ch);
return $result;
} ?>
Hope this will help!
This exception is thrown when you have used special characters.Try removing the , before the fullstop.
And to make it responsive like adding accept and reject you can look into the firebase documentation
this is a good explanation
Related
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 have a little problem: If I send a notification to my android device via php from the web, a notification gets built, but isn't vibrating outside the app. It is only vibrating while I am inside the app.
Here are my codes:
PHP:
function send_notification ($token, $message, $Raum, $Notruf){
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array('to' => $token, 'notification' => array('body' => "Raum ".$Raum.", Notruf ".$Notruf), 'data' => array ('message' => $message));
$headers = array ('Authorization:key = (HERE IS MY AUTH 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_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
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;
}
$sql = 'SELECT token FROM devices as d, Sani as s WHERE d.sean = s.sean AND s.Status!=0';
$result = mysqli_query($db, $sql);
$tokens = array ();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)){
$tokens[] = $row["token"];
}
}
mysqli_close($db);
$message = array ("message" => "Raum ".$Raum.", Notruf ".$Notruf);
for ($i = 0; $i < count($tokens); ++$i) {
$message_status = send_notification ($tokens[$i], $message, $Raum, $Notruf);
echo $message_status;
}
My Android Notification Code:
public class MyNotificationManager {
private Context mCtx;
private static MyNotificationManager mInstance;
private MyNotificationManager(Context context){
mCtx=context;
}
public static synchronized MyNotificationManager getInstance(Context context){
if(mInstance== null){
mInstance = new MyNotificationManager(context);
}
return mInstance;
}
public void displayNotification(String title, String body){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mCtx, Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.sirenlight)
.setContentTitle(title)
.setVibrate(new long[] {0, 5000, 100, 5000, 100, 5000, 100, 5000, 100, 5000, 100, 5000})
.setContentText(body);
Intent intent = new Intent(mCtx, EinsatzInterface.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mCtx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);
if(mNotificationManager!=null){
mNotificationManager.notify(1, mBuilder.build());
}
}
}
I couldn't get any fixes online, so I am asking here.
How I said, the vibration is working, but only inside the app. If I close it, even without stopping the process, it only shows the notification and doesn't vibrate or show the correct logo.
When inside the app the notification looks like this (vibrating and icon showing):
When outside the app the notification looks like this (not vibrating and icon not showing):
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");;
}