Flutter firebase messaging not receiving notifications - android

I am currently working on flutter notification using firebase messaging, I couldn't receive any notification. I sent the notification via server using curl, I could get it work in native android app (Android Studio) but not in flutter, any help would be appreciated. Below is my code.
Flutter Notification code
class FirebaseNotifications {
FirebaseMessaging _firebaseMessaging;
void setUpFirebase() {
_firebaseMessaging = FirebaseMessaging();
firebaseCloudMessaging_Listeners();
}
void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();
_firebaseMessaging.getToken().then((token) {
print(token);
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
},
onResume: (Map<String, dynamic> message) async {
print('on resume $message');
},
onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
},
);
}
void iOS_Permission() {
_firebaseMessaging.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
}
Android Studio code
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> params = remoteMessage.getData();
JSONObject object = new JSONObject(params);
showNotification(remoteMessage);
}
private void showNotification(RemoteMessage remoteMessage) {
Map data = remoteMessage.getData();
String mesg = "New Notification";
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.GREEN);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{0, 250, 250, 250});
mNotificationManager.createNotificationChannel(mChannel);
builder = new NotificationCompat.Builder(this, id);
intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentTitle(data.get("title").toString()) // required
//.setStyle(new
NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification()
.getBod
y().toString()))
.setStyle(new
NotificationCompat.BigTextStyle().bigText(mesg)) //custom data
.setSmallIcon(R.drawable.ic_stat_notification_icon4) //
required
.setContentText(mesg) // custom data
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{0, 250, 250, 250});
}
}
Server side code
function sendtoUser($sendingTarget, $acc_name, $type_message,
$type_of_transaction, $check_amount)
{
#API access key from Google API's Console
$API_ACCESS_KEY = "adazxc";
$registrationIds = $sendingTarget;
#prep the bundle
$fields = array(
'to' => $registrationIds,
'data' => array(
'title' => 'my title',
'keyValue' => true,
'receiverName' => $acc_name,
'transType' => $type_of_transaction,
'totalAmount' => $check_amount
),
);
$headers = array(
'Authorization: key=' . $API_ACCESS_KEY,
'Content-Type: application/json'
);
#Send Reponse To FireBase Server
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
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);
}
EDIT
I somehow can receive notification but I noticed that my status bar not receiving the notification but it is printed in the console, however, when I close the app I can get the notification. So how do I able to receive notification in both situation?

data tag only for transferring more information to app, like where it has to redirect, image etc.. you have to add notification tag to display notification on status bar.
its seems you havent added notification content, please refer below sample message and configure same, it'll work
{
"notification": {
"body": "body",
"title": "title"
},
"priority": "high",
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"image": "https://ibin.co/2t1lLdpfS06F.png",
},
"to": <fcm_token>
}

From the docs:
Depending on a devices state, incoming messages are handled differently.
State
Description
Foreground
When the application is open, in view & in use.
Background
When the application is open, however in the background (minimised). This typically occurs when the user has pressed the "home" button on the device, has switched to another app via the app switcher or has the application open on a different tab (web).
Terminated
When the device is locked or the application is not running. The user can terminate an app by "swiping it away" via the app switcher UI on the device or closing a tab (web).
And this:
Notification messages which arrive whilst the application is in the foreground will not display a visible notification by default.
If your app is currently opened and in the foreground, the notification will not be shown even if it was sent successfully. You can confirm this by opening the snackbar in the notification event handler like below:
FirebaseMessaging.onMessage.listen((message) {
print('Got a message whilst in the foreground!');
if (message.notification != null) {
final snackBar = SnackBar(
content: Text(message.notification?.title ?? '', maxLines: 2),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
});
If you're working with android and you want to display notification when in the foreground, you can use flutter_local_notifications package as suggested from the FCM docs here.

Some checks (Version numbers may change):
Add google-services.json (Download from firebase console) to
android/app/
In android/build.gradle:
Add google() to repositories
Add classpath 'com.google.gms:google-services:4.2.0' to dependencies
In android/app/build.gradle:
Add implementation 'com.google.firebase:firebase-messaging:18.0.0' to
dependencies
Add apply plugin: 'com.google.gms.google-services' at the end
Have the applicationId the same like package_name in the
google-services.jon

For what it's worth, I had an issue with receiving onMessage notifications today (didn't try onResume or onLaunch) when it was working fine yesterday. No errors in the Functions logs and tokens were all the same.
Try restarting your device -- this seems to be the most consistent way to fix this if your functions were previously working.
Also, if the messaging seems slow at first, this may be due to cold starting when you aren't using the functions for a while (see this SO question for a bit more information).

Most of the scenarios are already mentioned here. However, along with the checklist mentioned by #Zerj, I would like to add one more point.
Check if your project has environment flavors for dev, staging, prod etc. In that case, the google-services.json file would reside in the respective folders (android/app/development, etc) instead of at the android/app level.
If the above method too gives some problems for you, you can hardcode the credentials in the flavor's MainActivity file using FirebaseOptions class. You can find the usage here
More info about flavors - https://firebase.google.com/docs/projects/multiprojects

You may miss manual configuration for android (as well as ios if required), refer below link
http://myhexaville.com/2018/04/09/flutter-push-notifications-with-firebase-cloud-messaging/

Related

FCM Push Notification not received after some time or reboot

I have a little problem here that I, unfortunately, I currently can't really solve it by myself, so asking for help here.
I am trying to build push notifications in my app and I am using FCM.
For this whole process I use:
Android application with firebase
PHP Script to send FCM Push Notifications
MySQL DB to store tokens.
It works the following way: Each time a new token is generated, I send this token to my MySQL db where it is then stored. A PHP script that I have reads db for all tokens that it can find and sends push notification to all the devices.
I have watched many youtube videos and read multiple articles on how to do that and I managed to get it working, however, it is quite unstable and I can't get it to work persistently.
Here are some scenarios where it doesn't work for unknown to me reason.
Case 1:
Day 1:
I just installed application, launched it and then put it in background. Sent Push and received it successfully. In 3-4 hours I send notification again and successfully receive it.
Day 2: Right after Day 1, at 1 AM in the morning of Day 2 I sent notification again and it was never received. I went to bed and in the morning the message was never received still so I tried to send message again and my php script says that message was received (as per Firebase console response), but the notification is never shown.
-- Note: I have also implemented a method inside "onMessageReceived()" to save the message to MySQL so that I can personally monitor if the device at least received the message to better understand how it works, but the device never even received it.
Case 2:
Day 1: Installed application. Launched it, closed it and sent Push. Successfully received.
In 1 hour, I reboot my phone. 20 mins later I tried sending Push but I never received it. I tried launching application and putting it in background, yet I still received nothing.
I tried sending some Notifications not with PHP script, but with FCM Console, but still nothing.
Only after 10 minutes I received Notifications that I send some time ago, yet I tried sending notifications with my PHP script and it still didn't work and only after few more minutes I could send notifications with my PHP again.
The behavior that I described above is simply very chaotic to my understanding. I don't follow any logic whatsoever.
My Code:
PHP Script:
<?php
function send_notification ($tokens, $data, $priority)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'delay_while_idle' => false,
'android' => $priority,
'data' => $data,
'registration_ids' => $tokens
);
//var_dump($fields);
$headers = array(
'Authorization: key = KJAdkashdkhaiiwueyIhAXZ.....',
'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);
print($ch);
print("<br>");
print("<br>");
print($result);
print("<br>");
print("<br>");
print(json_encode($fields));
print("<br>");
print("<br>");
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect('ip_address', 'username', "password", 'mydatabasename');
$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);
$data = array(
'title' => 'This is title of the message',
'body' => 'This is body of the message',
'contents' => 'Simple contents of the message'
);
$android = array(
'priority' => 'high'
);
$message_status = send_notification($tokens, $data, $android);
echo $message_status;
Android:
MyFirebaseMessagingService
class MyFirebaseMessagingService : FirebaseMessagingService() {
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// Save received message to MySQL
HUC.success()
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
}
// Send notification containing the body of data payload
sendNotification(remoteMessage.data["body"].toString())
}
// [END receive_message]
// [START on_new_token]
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
override fun onNewToken(token: String) {
Log.d(TAG, "Refreshed token: $token")
// Saving my registration token to MySQL
sendRegistrationToServer(token)
}
// [END on_new_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private fun sendRegistrationToServer(token: String?) {
CoroutineScope(IO).launch {
// HttpURLConnection function to save token to MySQL
val response = HUC.saveToken(token)
withContext(Main){
Log.d(TAG, "Server response: $response")
}
}
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private fun sendNotification(messageBody: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT
)
val channelId = getString(R.string.default_notification_channel_id)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
}
companion object {
private const val TAG = "MyFirebaseMsgService"
}
}
Please help me understand here. Maybe I am doing something wrong or perhaps I am missing something.
As a matter of fact, everything started working properly when I hard reset my phone which leads me to believe that it was internal phone problem rather than my implementation.

How to send push notification to android devices even when app is killed?

I am able to send notification when app is in foreground and background. But cant manage to send it when app is killed i.e app not running in background. Other app in my mobile are able to send me notification even when they are running in background. I am using oreo version.
I too replaced 'notification' with 'data' which didnt made a difference.
I already added the custom notification on onMessageReceived method, the 'notification' and 'data' both gives notification on foreground and background. Only difference is 'data' runs onMessageReceived method while on background too. But on both , notification is not received when app is killed.I have tried following code on php. What am i doing wrong?
function sendPushNotification($token) {
$url = "https://fcm.googleapis.com/fcm/send";
$serverKey = 'AAAA.....theKey';
$title = "My App";
$body = "hello there!!";
$notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
/* if ($response === FALSE) {
die('FCM Send Error: ' . curl_error($ch));
}*/
curl_close($ch);
// echo "<br>";
return $response;
}
Following in onMessageReceived method:
For 'notification':
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("apkflow","onMessageReceived Started");
if (remoteMessage.getNotification() != null) {
title = remoteMessage.getNotification().getTitle();
body = remoteMessage.getNotification().getBody();
Log.d("apkflow","title = " + title);
Log.d("apkflow","body = " + body);
}
}
For 'data':
title = remoteMessage.getData().get("title");
body = remoteMessage.getData().get("body");
UPDATE::
I got the solution now !! Its due to the mobile recents updates. In mobiles like Vivo, oppo, xiomi and so on , when app is cleared, it force stop the app forcing to stop all the services. So, the FCM services is also stopped and no any notification is received on mobile. So, for getting notification, user must allow the app to run in background "allow in background" must be checked. This solves the problem. If you still have problem , leave a comment!!
Messages with both notification and data payload, when received in the
background.
Change the notification type data
$arrayToSend = array('to' => $token, 'data' => $notification,'priority'=>'high');
Please go through the below documentation
https://firebase.google.com/docs/cloud-messaging/android/receive
You have to create the custom notification.
private void setNotification(RemoteMessage content) {
Log.d(TAG, "custom notification: ");
Intent intent = new Intent(this, NotificationActivity.class);
if (!content.getData().get("url").isEmpty())
intent.putExtra("url", content.getData().get("url"));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.custome_notification);
remoteViews.setTextViewText(R.id.tvTime, currentDate());
remoteViews.setTextViewText(R.id.text, content.getData().get("text"));
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, getPackageName())
.setSmallIcon(R.drawable.ic_alert)
.setContent(remoteViews)
.setAutoCancel(true)
.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// To avoid replacing old notification by new one. To set new id for every new Notification following notifications.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(getPackageName(), "AppName", importance);
notificationManager.createNotificationChannel(mChannel);
}
int notifyId = (int) System.currentTimeMillis();
notificationManager.notify(notifyId, notificationBuilder.build());
}

How to show custom UI for firebase notification when the app is in background?

I use this class to show notification whit my own UI (RemoteViews) , received from firebase console. This works fine when the app is foreground , but when the app is in background, notification displayed in default style of device.What should I do to show notification in my own UI even the app is foreground or background?
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "Mehdi";
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
super.onMessageReceived(remoteMessage);
if (remoteMessage.getNotification() != null)
{
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.payam_notification_layout);
contentView.setTextViewText(R.id.payam,remoteMessage.getNotification().getBody());
String channelId = "Default";
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.drawable.status_icon_delivered)
.setLargeIcon(BitmapFactory.decodeResource( getResources(), R.mipmap.icon))
.setSound(Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.notification))
.setCustomBigContentView(contentView)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, mBuilder.build());
}
}
}
Note : thanks for the correct answer, I could send notification with my own UI by using this link , even app is in background or foreground :
http://www.androiddeft.com/2017/11/18/push-notification-android-firebase-php/
Actually tow type of payload we are using when sending the notification,
One is Notification Payload and another one is Data Payload.
Notification payload manage notification automatically when you are in the foreground they call onMessageReceived from firebase service but when are you in Background they do not call onMessageReceived,
So for the solution purpose just send data in Data payload and remove Notification payload so You can get the notification in onMessageReceived in every state and you can manage UI of that.
Check bellow example
function sendFCMNotification($message,$id) {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array (
'to' => $id,
'data' => array (
"body" => $message,
"title" => "Title Text"
)
);
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . "Legcy Key",
'Content-Type: application/json'
);

'500 - internal server error' response from firebase server on sending a downstream 'data' message

I'm sending a downstream message to a single device from app server via Firebase server. I'm using the devices reg token that was passed to the apps server. app server code is
$firebase_token = $request->input('token');
$skey = env('FCM_SERVER_KEY');
$client = new Client(['verify' => false]);
$response = $client->request('POST', 'https://fcm.googleapis.com/fcm/send', [
'headers' => [
'Authorization:key=' => $skey,
'Content-Type' => 'application/json'
],
'json' => ['to' => $firebase_token, 'data' => ['message' => 'This is Genius']]
]);
I'm receiving the following message from my android app (cause i'm testing out FCM and i'm sending the $response back to my app on the emulator.)
Its the same message I'm getting on Postman.
{"message":
"Server error: `POST https:\/\/fcm.googleapis.com\/fcm\/send` resulted in a
`500 Internal Server Error` response:\n
<HTML>\n
<HEAD>\n
<TITLE>Internal Server Error<\/TITLE>\n
<\/HEAD>\n
<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\">\n
<H1>Internal ServerE(truncated...)\n",
"code":500,
"status_code":500,"debug"
...
I'm using Laravel and Guzzle Client to deliver the message to the FCM server, I tried sending a message to my emulator from my Firebase console and it marked the message as completed but I didn't receive it on my app/emualtor. This is my onMessageReceived method inside my FirebaseMessagingService class
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(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);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("FCM Test")
.setContentText(message)
.setSmallIcon(R.drawable.com_facebook_button_send_icon_blue)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
I'm not sure whats wrong with my setup. Any help will be appreciated.
make sure that your credential is correct
it may not received to emulator because of internet connection issues

Open a specific view in ionic app when user taps on push notification

I know this question has been asked and answered many times but none of the solution is working for me.
I have followed ionic.io documentation https://docs.ionic.io/services/push/ to implement push notification and it works fine when app is in foreground. I am also able to receive notification when app is closed. Now when user clicks on that notification, I want to open a specific view.
As per documentation, To handle push notifications in your app, we need to listen to the cloud:push:notification event using angular’s $on.
$scope.$on('cloud:push:notification', function(event, data) {
var msg = data.message;
alert(msg.title + ': ' + msg.text);
});
This code is working fine when app is foreground. But when app is closed and user opens the app by tapping the push notification, I want to open specific view/controller.
I have placed the above code in .run function and outside $ionicPlatform.ready function.
Here is my code to call FCM Rest service
function sendFCMNotification($request_data){
$ch = curl_init("https://fcm.googleapis.com/fcm/send");
//The device token.
$token = $request_data['device_id'];
//Title of the Notification.
$title = $request_data['title'];
//Body of the Notification.
$body = $request_data['body'];
//Creating the notification array.
$notification = array('title' =>$title , 'body' => $body,'content-available'=> '1');
//This array contains, the token and the notification. The 'to' attribute stores the token.
$arrayToSend = array('to' => $token, 'notification' => $notification);
//Generating JSON encoded string form the above array.
$json = json_encode($arrayToSend);
//Setup headers:
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key= {MY GCM KEY}';
//Setup curl, add headers and post parameters.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
curl_exec($ch);
//Close request
curl_close($ch);
}
Can anyone help me in achieving this?
Pushwoosh provides a method which can tell us if the app has been launched by clicking push notification or not.
https://rawgit.com/Pushwoosh/pushwoosh-phonegap-3.0-plugin/master/Documentation/files/PushNotification-js.html#PushNotification.getLaunchNotification
Is there any similar function in ionic push plugin?
If you are sending a CURL req to ionic for push use this data structure
$notficationHolder =array(
"user_ids" => array(),
"profile" => "push",
"notification"=>array(
"android"=>array(
"title"=>'TITLE',
"message"=>"You have a notification",
"sound" => "sound",
"icon_color" => "#FA2B2E",
"icon" => "notification",
/* "image" => "https://pbs.twimg.com/profile_images/617058765167329280/9BkeDJlV.png", */
"payload" => array(
'$state'=> 'main.myProfile',
'$stateParams'=> array()
)
),
"ios"=>array(
"sound" => "default",
"payload" => array(
'$state'=> 'main.myProfile',
'$stateParams'=> array()
)
)
)
);
This is an array. json encode it and curl it to ionic. The catch is your payload property in the notification object.
you need to add in payload attribute
{"$state":'yourStateName','$stateParams':{'paramOne':1,'paramTwo':2}}

Categories

Resources